1

您将如何分配[5, 6, 7]to的每个元素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

4 回答 4

2

适用于任何长度的数组的通用解决方案,并使元素的索引成为哈希中的键是:

Hash[row.each_with_index.map {|elem, i| [i, elem]}]
于 2013-04-08T15:22:38.693 回答
1
row.keys.zip([5, 6, 7]){|kv| row.store(*kv)}
于 2013-04-08T15:09:02.927 回答
0
array = [5, 6, 7]
Hash[*array.each_with_index.map{ |elem, idx| [idx + 1, elem]}.flatten]

结果

{1=>5, 2=>6, 3=>7}
于 2013-04-08T15:10:35.230 回答
0

您可以尝试以下方法:

row = {1=>0, 2=>1, 3=>0}
p Hash[*(row.keys.zip([5, 6, 7]).flatten)]

#=> {1=>5, 2=>6, 3=>7}
于 2013-04-08T15:58:25.307 回答