Constructing a Hash from a function and its domain

T

Tim L

Hi:

Another newbie question.

I want to make a Hash from an enumerable set of values to which a function
can be applied, with these values the keys of the Hash, and the results of
the function applied to the values (of the enumerable set) the corresponding
values of the Hash.

If the set of values I want is arr, and the function is f, I was expecting
to be able to pass something based on

(arr.collect {|k| f(k)}).flatten

to the Hash method [], but somehow I want to tell Ruby to take the elements
of my array as the arguments to this method, rather than the array itself.

How can I do this?

I worked out another way to do this, viz.:

#beginning of code
class Hash

def Hash.MakeFromDomainAndProc(domain, &proc)
h = {}
domain.each {|d| h[d] = proc.call(d) }
h
end

end

#end of code

which I like, and makes me think warm thoughts about Ruby. In fact,
thinking abstractly, it strikes me that a Hash is nothing other than a
function defined on an enumerable set, so I would have half expected there
to be a built in Hash constructor method such as this.

Tim L
 
R

Robert Klemme

Tim said:
Hi:

Another newbie question.

I want to make a Hash from an enumerable set of values to which a function
can be applied, with these values the keys of the Hash, and the results of
the function applied to the values (of the enumerable set) the corresponding
values of the Hash.

If the set of values I want is arr, and the function is f, I was expecting
to be able to pass something based on

(arr.collect {|k| f(k)}).flatten

to the Hash method [], but somehow I want to tell Ruby to take the elements
of my array as the arguments to this method, rather than the array itself.

How can I do this?

Several ways:

Hash[*arr.collect {|k| f(k)}]
arr.inject({}) {|h,v| h[v]=f(v);h}

# lazy
Hash.new {|h,k| h[k]=f(k)}

See also memoize.

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top