将两个arrays组合成哈希
我有两个arrays:
members = ["Matt Anderson", "Justin Biltonen", "Jordan Luff", "Jeremy London"] instruments = ["guitar, vocals", "guitar", "bass", "drums"]
我想要做的就是把这些结合起来,这样生成的数据结构就像这样:
{"Matt Anderson"=>["guitar", "vocals"], "Justin Biltonen"=>"guitar", "Jordan Luff"=>"bass", "Jeremy London"=>"drums"}
注意“Matt Anderson”的值现在是数组而不是string。 任何Ruby的巫师都在乎这个镜头?
我知道Hash[*members.zip(instruments).flatten]
结合他们几乎是我想要的方式,但怎么把“吉他,人声”string变成一个数组? 谢谢。
使用map
和split
将仪器串转换成数组:
instruments.map {|i| i.include?(',') ? (i.split /, /) : i}
然后使用Hash[]
和zip
将组合members
与instruments
:
Hash[members.zip(instruments.map {|i| i.include?(',') ? (i.split /, /) : i})]
要得到
{"Jeremy London"=>"drums", "Matt Anderson"=>["guitar", "vocals"], "Jordan Luff"=>"bass", "Justin Biltonen"=>"guitar"}
如果你不在意单项清单是否也是数组,你可以使用这个更简单的解决scheme:
Hash[members.zip(instruments.map {|i| i.split /, /})]
这给你这个:
{"Jeremy London"=>["drums"], "Matt Anderson"=>["guitar", "vocals"], "Jordan Luff"=>["bass"], "Justin Biltonen"=>["guitar"]}
正如Rafe Kettler所发布的,使用zip是最好的select。
Hash[members.zip(instruments)]
例子01
k = ['a', 'b', 'c'] v = ['aa', 'bb'] h = {} k.zip(v) { |a,b| h[a.to_sym] = b } # => nil ph # => {:a=>"aa", :b=>"bb", :c=>nil}
例子02
k = ['a', 'b', 'c'] v = ['aa', 'bb', ['aaa','bbb']] h = {} k.zip(v) { |a,b| h[a.to_sym] = b } ph # => {:a=>"aa", :b=>"bb", :c=>["aaa", "bbb"]}
这是做你想做的最好和最干净的方式。
Hash[members.zip(instruments.map{|i| i.include?(',') ? i.split(',') : i})]
请享用!
h = {} members.each_with_index do |el,ix| h[el] = instruments[ix].include?(",") ? instruments[ix].split(",").to_a : instruments[ix] end h
members.inject({}) { |m, e| t = instruments.delete_at(0).split(','); m[e] = t.size > 1 ? t : t[0]; m }
如果你不关心结果中的1元素数组,你可以使用:
members.inject({}) { |m, e| m[e] = instruments.delete_at(0).split(','); m }
h = {} members.each_with_index {|item, index| h.store(item,instruments[index].split) }