红宝石-将两个数组合并为哈希

我有两个数组:

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”的值现在是一个数组而不是字符串。 任何Ruby向导都愿意试一试吗?

我知道Hash[*members.zip(instruments).flatten]几乎以我想要的方式将它们组合在一起,但是首先将“吉他,人声”字符串转换为数组呢? 谢谢。

Michael Irwin asked 2019-11-15T06:51:49Z
7个解决方案
104 votes

正如Rafe Kettler所说,使用zip是必经之路。

Hash[members.zip(instruments)] 
Raj answered 2019-11-15T06:53:03Z
45 votes

使用Hash[]zip将乐器字符串转换为数组:

instruments.map {|i| i.include?(',') ? (i.split /, /) : i}

然后使用Hash[]zipmembersinstruments结合:

Hash[members.zip(instruments.map {|i| i.include?(',') ? (i.split /, /) : i})]

要得到

{"Jeremy London"=>"drums",
 "Matt Anderson"=>["guitar", "vocals"],
 "Jordan Luff"=>"bass",
 "Justin Biltonen"=>"guitar"}

如果您不在乎单项列表是否也是数组,则可以使用以下更简单的解决方案:

Hash[members.zip(instruments.map {|i| i.split /, /})]

这给你这个:

{"Jeremy London"=>["drums"],
 "Matt Anderson"=>["guitar", "vocals"],
 "Jordan Luff"=>["bass"],
 "Justin Biltonen"=>["guitar"]}
nohat answered 2019-11-15T06:52:37Z
9 votes

示例01

k = ['a', 'b', 'c']
v = ['aa', 'bb']
h = {}

k.zip(v) { |a,b| h[a.to_sym] = b } 
# => nil

p h 
# => {: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 }
p h 
# => {:a=>"aa", :b=>"bb", :c=>["aaa", "bbb"]}
coolesting answered 2019-11-15T06:53:35Z
3 votes

这是做您想要的最好和最干净的方法。

Hash[members.zip(instruments.map{|i| i.include?(',') ? i.split(',') : i})]

请享用!

Mario Viapiano answered 2019-11-15T06:54:04Z
1 votes
h = {}
members.each_with_index do |el,ix|
    h[el] = instruments[ix].include?(",") ? instruments[ix].split(",").to_a : instruments[ix]
end
h
Zabba answered 2019-11-15T06:54:23Z
1 votes
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 }
DigitalRoss answered 2019-11-15T06:54:50Z
0 votes
h = {}

members.each_with_index {|item, index|
     h.store(item,instruments[index].split)
}
macarthy answered 2019-11-15T06:55:10Z
translate from https://stackoverflow.com:/questions/5174913/combine-two-arrays-into-hash