如何将数组转换为具有数组元素作为哈希键和所有哈希值都设置为给定值的哈希

时间:2022-05-26 21:42:47

Using Ruby 2.1 (with ActiveSupport 3.x, if that helps), I want to convert an array like this:

使用Ruby 2.1(使用ActiveSupport 3)。x,如果有帮助的话),我想转换一个这样的数组:

[ :apples, :bananas, :strawberries ]

Into a hash like this:

变成这样的散列:

{ :apples => 20, :bananas => 20, :strawberries => 20 }

Technically, this works:

从技术上讲,这是:

array = [ :apples, :bananas, :strawberries ]
hash = Hash[array.zip(Array.new(array.length, 20))]
# => {:apples=>20, :bananas=>20, :strawberries=>20}

But that seems really clunky, and I feel like there's a more straightforward way to do this. Is there one?

但这似乎真的很笨拙,我觉得有一种更直接的方法可以做到这一点。有一个吗?

I looked at Enumerable#zip as well as the default value option for Hash#new but didn't see anything providing a simple method for this conversion.

我查看了Enumerable#zip以及Hash#new的默认值选项,但是没有看到任何东西为这种转换提供简单的方法。

3 个解决方案

#1


2  

Another answer:

另一个回答:

ary = [ :apples, :bananas, :strawberries ]
Hash[[*ary.each_with_object(20)]]
# => {:apples=>20, :bananas=>20, :strawberries=>20}

Alternatively (as pointed out by the OP):

或(如OP所指出):

ary.each_with_object(20).to_h
# => {:apples=>20, :bananas=>20, :strawberries=>20}

Basically, calling each_with_object returns an Enumerator object of pairs consisting of each value and the number 20 (i.e. [:apples, 20], ...) which can subsequently be converted to a hash.

基本上,调用each_with_object会返回一个枚举器对象,其中包含每个值和数字20(例如[:apple, 20],…),然后可以将其转换为散列。

#2


3  

I think, Array#product will be helpful here :

我认为数组#产品在这里会有帮助:

ary = [ :apples, :bananas, :strawberries ]
Hash[ary.product([20])]
# => {:apples=>20, :bananas=>20, :strawberries=>20}

#3


2  

Use Hash[]:

使用哈希[]:

Hash[array.map { |f| [f, 20] }]

#1


2  

Another answer:

另一个回答:

ary = [ :apples, :bananas, :strawberries ]
Hash[[*ary.each_with_object(20)]]
# => {:apples=>20, :bananas=>20, :strawberries=>20}

Alternatively (as pointed out by the OP):

或(如OP所指出):

ary.each_with_object(20).to_h
# => {:apples=>20, :bananas=>20, :strawberries=>20}

Basically, calling each_with_object returns an Enumerator object of pairs consisting of each value and the number 20 (i.e. [:apples, 20], ...) which can subsequently be converted to a hash.

基本上,调用each_with_object会返回一个枚举器对象,其中包含每个值和数字20(例如[:apple, 20],…),然后可以将其转换为散列。

#2


3  

I think, Array#product will be helpful here :

我认为数组#产品在这里会有帮助:

ary = [ :apples, :bananas, :strawberries ]
Hash[ary.product([20])]
# => {:apples=>20, :bananas=>20, :strawberries=>20}

#3


2  

Use Hash[]:

使用哈希[]:

Hash[array.map { |f| [f, 20] }]