将两个数组组合成哈希 [英] Combine two Arrays into Hash
问题描述
我有两个数组:
members = ["Matt Anderson", "Justin Biltonen", "Jordan Luff", "Jeremy London"]
instruments = ["guitar, vocals", "guitar", "bass", "drums"]
我想做的是将这些组合起来,这样得到的数据结构就是一个像这样的哈希:
What I would like to do is combine these so that the resulting data structure is a Hash like so:
{"Matt Anderson"=>["guitar", "vocals"], "Justin Biltonen"=>"guitar", "Jordan Luff"=>"bass", "Jeremy London"=>"drums"}
请注意,Matt Anderson"的值现在是一个数组而不是字符串.任何 Ruby 向导都愿意试一试吗?
Note the value for "Matt Anderson" is now an Array instead of a string. Any Ruby wizards care to give this a shot?
我知道Hash[*members.zip(instruments).flatten]
几乎以我想要的方式组合它们,但是如何转动吉他,人声"字符串先放入一个数组?谢谢.
I know Hash[*members.zip(instruments).flatten]
combines them almost the way I want, but what about turning the "guitars, vocals" string into an array first? Thanks.
推荐答案
使用 map
和 split
将乐器字符串转换为数组:
Use map
and split
to convert the instrument strings into arrays:
instruments.map {|i| i.include?(',') ? (i.split /, /) : i}
然后使用Hash[]
和zip
将members
与instruments
结合起来:
Then use Hash[]
and zip
to combine members
with 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"}
如果你不关心单项列表是否也是数组,你可以使用这个更简单的解决方案:
If you don't care if the single-item lists are also arrays, you can use this simpler solution:
Hash[members.zip(instruments.map {|i| i.split /, /})]
它给了你这个:
{"Jeremy London"=>["drums"],
"Matt Anderson"=>["guitar", "vocals"],
"Jordan Luff"=>["bass"],
"Justin Biltonen"=>["guitar"]}
这篇关于将两个数组组合成哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!