Ruby - mapping an array to hashmap

Ji Mun picture Ji Mun · Oct 22, 2012 · Viewed 62.1k times · Source

I have an array, and a function that returns a value given a value. Ultimately I want to create a hashmap that has the values of the array as key value, and the result of f(key_value) as the value. Is there a clean, simple way, like similar to each/map of Array, of doing this using block?

So something that is equivalent to

hsh = {}
[1,2,3,4].each do |x|
  hsh[x] = f(x)
end

but looks more similar to this, in that it's simple and one line?

results = array.map { | x | f(x) }

Answer

Knotty66 picture Knotty66 · Jun 17, 2015

Note that since Ruby 2.1.0 you can also use Array#to_h, like this:

[1,2,3,4].map{ |x| [x, f(x)] }.to_h