说我有一个字符串,如
"@a ipsum lorem @b dolor sit amet @c consectetur adipisicing"
我想转换为数组(或散列,或键和值的某种模式)
{ @a => "ipsum lorem", @b => "dolor sit amet", @c => "consectetur adipisicing" }
这是可能的,如果可以的话怎么办呢?
一些要点:
@
答案 0 :(得分:4)
s = "@a ipsum lorem @b dolor sit amet @c consectetur adipisicing"
Hash[s.split(" ").slice_before(/@/).map{|k,*v|[k,v.join(" ")]}]
#=> {"@a"=>"ipsum lorem", "@b"=>"dolor sit amet", "@c"=>"consectetur adipisicing"}
答案 1 :(得分:3)
Hash[s.scan(/\@\w+/).zip s.split(/\s?\@\w+\s/).drop(1)]
答案 2 :(得分:1)
s = "@a ipsum lorem @b dolor sit amet @c consectetur adipisicing"
hs = {}
s.split('@').drop(1).each{|val| tmp = val.split(' '); hs["@#{tmp.shift}"] = tmp.join(' ') }
# puts hs
#=>{"@a"=>"ipsum lorem", "@b"=>"dolor sit amet", "@c"=>"consectetur adipisicing"}
答案 3 :(得分:0)
Hash[
string
.scan(/(@\S+)\s+(.+?)(?=\s+@|\z)/)
.map{|k, v| [instance_variable_get(k), v]}
]