In Ruby, how do I make a hash from an array?

Posted by Wizzlewott on Stack Overflow See other posts from Stack Overflow or by Wizzlewott
Published on 2010-05-31T12:12:04Z Indexed on 2010/05/31 12:23 UTC
Read the original article Hit count: 146

Filed under:
|
|

I have a simple array:

arr = ["apples", "bananas", "coconuts", "watermelons"]

I also have a function f that will perform an operation on a single string input and return a value. This operation is very expensive, so I would like to memoize the results in the hash.

I know I can make the desired hash with something like this:

h = {}
arr.each { |a| h[a] = f(a) }

What I'd like to do is not have to initialize h, so that I can just write something like this:

h = arr.(???) { |a| a => f(a) }

Can that be done?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about array