jeff_alexander_44
3/24/2007 3:24:00 PM
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.