Ruby - mapping an array to hashmap

81,485

Solution 1

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[10]
hash.inspect #=> { 10 => whatever_the_result_is }

Solution 2

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

Solution 3

Ruby 2.6.0 enables passing a block to the to_h-method. This enables an even shorter syntax for creating a hash from an array:

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

Solution 4

You need each_with_object.

def f x
  x * 2
end

t = [1, 2, 3, 4].each_with_object({}) do |x, memo|
  memo[x] = f(x)
end

t # => {1=>2, 2=>4, 3=>6, 4=>8}

Another one:

t2 = [1, 2, 3, 4].map{|x| [x, f(x)]}
Hash[t2] # => {1=>2, 2=>4, 3=>6, 4=>8}

Solution 5

Check out the Hash::[] method.

Hash[ [1,2,3,4].collect { |x| [x, f(x)] } ]
Share:
81,485

Related videos on Youtube

Ji Mun
Author by

Ji Mun

Updated on July 05, 2022

Comments

  • Ji Mun
    Ji Mun almost 2 years

    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) }
    
  • Oded Niv
    Oded Niv over 6 years
    Note that this doesn't work with lazy enumerators, but Ruby 2.1.0's .to_h does.
  • Paul van Leeuwen
    Paul van Leeuwen over 4 years
    for those reading this answer and liking it: see also alternative flavor in answer by Timitry (currently way down the list)