您如何将[5, 6, 7]
的每个元素分配给row
的值,并使row
成为{1=>5, 2=>6, 3=>7}
?
row = {1=>0, 2=>1, 3=>0}
#this following line doesn't work of course
row.values = [5, 6, 7]
#NoMethodError: undefined method `values=' for {1=>0, 2=>1, 3=>0}:Hash
row
#I want: {1=>5, 2=>6, 3=>7}
答案 0 :(得分:2)
适用于任何数组长度的通用解决方案,并使元素的索引成为哈希中的键:
Hash[row.each_with_index.map {|elem, i| [i, elem]}]
答案 1 :(得分:1)
row.keys.zip([5, 6, 7]){|kv| row.store(*kv)}
答案 2 :(得分:0)
array = [5, 6, 7]
Hash[*array.each_with_index.map{ |elem, idx| [idx + 1, elem]}.flatten]
结果
{1=>5, 2=>6, 3=>7}
答案 3 :(得分:0)
您可以尝试以下方法:
row = {1=>0, 2=>1, 3=>0}
p Hash[*(row.keys.zip([5, 6, 7]).flatten)]
#=> {1=>5, 2=>6, 3=>7}