[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Constructing a Hash from a function and its domain

Tim L

4/12/2006 10:46:00 AM

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


1 Answer

Robert Klemme

4/12/2006 10:55:00 AM

0

Tim L wrote:
> 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