1

[5, 6, 7]の各要素をtorowの値にどのように割り当てて、に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

A generic solution that works for any length of the array, and makes the index of the element the key in the hash is:

Hash[row.each_with_index.map {|elem, i| [i, elem]}]
于 2013-04-08T15:22:38.693 に答える
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 に答える