From: Andrew Timberlake Date: 2009-04-29T15:13:31+09:00 Subject: Re: Hash#map On Wed, Apr 29, 2009 at 8:00 AM, Fredrik wrote: > Is there any good reason why Hash#map does not give back a Hash (Ruby > 1.8 but same in 1.9 as far as I know)? I often find myself writing > these kind of things: > > newhash = oldhash.inject({}) { |h,(k,v)| h[k] = some_operation(v); h } > > but that doesn't look pretty at all in my opinion. I want to just > write like this: > > newhash = oldhash.map { |k,v| some_operation(v) } > > I finally got around to change this behaviour for my own code, but are > all Ruby users supposed to invent this wheel on their own? Wouldn't it > be better if Hash#map behaved like this? Or is there something I am > missing? > > class Hash >  def hashmap >    self.inject({}) do |newhash, (k,v)| >      newhash[k] = yield(k, v) >      newhash >    end >  end > end > > > Regards, > Fredrik > Becuase #map comes from form Enumerable (and is an alias for collect) enum.collect {| obj | block } => array enum.map {| obj | block } => array Returns a new array with the results of running block once for every element in enum. (1..4).collect {|i| i*i } #=> [1, 4, 9, 16] (1..4).collect { "cat" } #=> ["cat", "cat", "cat", "cat"] Andrew Timberlake http://ramblingsonrails.com http://www.linkedin.com/in/andrewtimberlake "I have never let my schooling interfere with my education" - Mark Twain