How to convert an array to a hash with array elements as hash keys and all hash values all set to given value

StackOverflow https://stackoverflow.com/questions/23684602

  •  23-07-2023
  •  | 
  •  

Вопрос

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

[ :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.

Это было полезно?

Решение

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):

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.

Другие советы

Use Hash[]:

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

I think, Array#product will be helpful here :

ary = [ :apples, :bananas, :strawberries ]
Hash[ary.product([20])]
# => {:apples=>20, :bananas=>20, :strawberries=>20}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top