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

时间:2022-12-10 11:34:53

How would you assign each element of [5, 6, 7] to row's values and make row become {1=>5, 2=>6, 3=>7}?

如何将[5,6,7]的每个元素分配给行的值并使行变为{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 个解决方案

#1


1  

row.keys.zip([5, 6, 7]){|kv| row.store(*kv)}

#2


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]}]

#3


0  

array = [5, 6, 7]
Hash[*array.each_with_index.map{ |elem, idx| [idx + 1, elem]}.flatten]

as result

{1=>5, 2=>6, 3=>7}

#4


0  

You can try the below:

您可以尝试以下方法:

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

#=> {1=>5, 2=>6, 3=>7}

#1


1  

row.keys.zip([5, 6, 7]){|kv| row.store(*kv)}

#2


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]}]

#3


0  

array = [5, 6, 7]
Hash[*array.each_with_index.map{ |elem, idx| [idx + 1, elem]}.flatten]

as result

{1=>5, 2=>6, 3=>7}

#4


0  

You can try the below:

您可以尝试以下方法:

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

#=> {1=>5, 2=>6, 3=>7}