From: ara.t.howard@... Date: 2007-03-25T00:44:20+09:00 Subject: Re: Hash#map_pairs On Sun, 25 Mar 2007 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. > > On second thought, it looks like this does the same thing: > > puts h.to_a.map { |k, v| "#{k} => #{v}" }.join(", ") > > But this fails to convey the programmer's idea in the same way that > map_pairs does. It is also needlessly inefficient, using a whole > extra temp array. harp:~ > cat a.rb 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(", ") puts h.map{ |k, v| "#{k} => #{v}" }.join(", ") ### ;-) harp:~ > ruby a.rb a => x, b => y a => x, b => y -a -- be kind whenever possible... it is always possible. - the dalai lama