From: Rick DeNatale Date: 2007-03-27T07:18:19+09:00 Subject: Re: Hash#map_pairs On 3/24/07, jeff_alexander_44@yahoo.com wrote: > class Hash > def map_pairs > result = Array.new > self.each_pair { |k, v| > result << yield(k, v) > } > result > end > end > > h = { > "a" => "x", > "b" => "y", > } > puts h.map_pairs { |k, v| "#{k} => #{v}" }.join(", ") > > I was surprised to discover there was no Hash#map_pairs. I have found > that chaining transformations is usually better than the > iterative/imperative style implied by Hash#each_pair. > In Ruby 1.9 , at least as it stands today, 'each-like' methods like each_pair will return an Enumerator if you don't give them a block, this allows a nice ability to chain transformations. rick@frodo:/public/rubysource/ruby1.8.5$ irb1.9 irb(main):001:0> {:a => 1, :b => 2}.each_pair => # irb(main):002:0> {:a => 1, :b => 2}.each_pair.map {|k,v| [v,k]} => [[2, :b], [1, :a]] irb(main):003:0> -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/