Ji Mun Ji Mun - 4 months ago 21x
Ruby Question

Ruby - mapping an array to hashmap

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)

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

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


You could also define the function as the hash's default value:

hash = Hash.new {|hash, key| hash[key] = f(key) }

Then when you lookup a value, the hash will calculate and store it on the fly.

hash.inspect #=> { 10 => whatever_the_result_is }