将一组值赋给Hash.values的最佳方法是什么

时间:2013-04-08 15:05:34

标签: ruby hash

您如何将[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}

4 个答案:

答案 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}