On Aug 23, 2010, at 6:55 PM, Glenn Little wrote:

Just wondering if there's an idiom for this.  Say I have an array "a",
each element is a hash:

a =[ {"a" => "eh", "b" => "bee"},
     {"c" => "see", "d" => "dee"},
     {"e" => "eee", "f" => "eff"}]

And I want to perform some sort of transformation on all the hash
values, but still end up with an array of the hashes.

Is there a cleaner (not necessarily shorter... I prefer elegantly
readable) way than:

a.each do |row|
row.each { |k,v| {row[k] => v.upcase }
end


IMO, that's about as good as it gets.

Probably just an email typo, but first, the example as shown must be v.upcase! or the original hash values will not be updated.

If the transformation is that simple, the whole thing could be a one liner if you liked:

a.each { |row| row.each { |k,v| {row[k] => v.upcase! }} }

However, I find that when the transformations are more complex, and an ! version of a method is not available, the more universally reliable pattern is to use:

 var[key] = new_value

instead of

 var[key] => new_value!

So in this contrived example:

shape_list = [
 {:name => 'circle', :size => 'small', :color => 'red'},
 {:name => 'square', :size => 'medium', :color => 'green'},
 {:name => 'triangle', :size => 'large', :color => 'blue'}
 ]
        
shape_list.each do |shape|
 shape.each do |key,value|
   if key == :name
          shape[key] = "__#{value.capitalize}"
   end
 end
end

using the = variation allows for more flexibility. Always using the = variation means I don't get stuck trying to remember if = or => is the right way.

Other than that tiny niggle, I haven't seen a particularly better way to step through an array of hashes. IMO, the clarity simply comes from good variable names.

-- gw


--
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby

Reply via email to