Ji Mun Ji Mun -5 years ago 175
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) }

Answer Source

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 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download