Martin Emde

On Mon, Aug 23, 2010 at 6:55 PM, Glenn Little <[email protected]> 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
>
> I'm not convinced that's even guaranteed to work... the mutating of
> the hash while it's being iterated over makes me uncomfortable.  I
> guess I could do something that felt safer (if not clunkier) by
> building a new hash inside each iteration, and appending it to a new
> array at the end of each iteration.
>
>
Mutating a hash while you're iterating over it is asking for trouble. Check
out the Hash and Enumerable docs for ideas. I'd probably do something along
the lines of: a.map { |r| r.inject({}) { ... } }

Another completely different way of approaching this: create a class for
your hash, make a new object with each hash that does your transform, and
keep an array of the objects.

Martin Emde

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

Reply via email to