From: "David A. Black" Date: 2008-05-14T00:16:36+09:00 Subject: Re: Updating all values in a Hash Hi -- On Tue, 13 May 2008, Sandro Paganotti wrote: > On Tue, May 13, 2008 at 2:20 PM, Paul Dugdale wrote: >> Does anyone know a good way to update all values in a hash. >> >> E.g. If I have a big hash with each element containing a string as a >> value, how can I make each string lower-case? >> -- >> Posted via http://www.ruby-forum.com/. >> >> > > I found this way > > h = Hash.new > > def h.[](val) > super.downcase > end > > h["ciao"] = "CIOOOO" > > puts h["ciao"] > # cioooo That's very resourceful (I'm fully in favor of extending individual objects), but I'm afraid it doesn't really do what Paul wants. All it does is downcase what you see when you do h[val]. But the actual value doesn't change: >> h = {} => {} >> def h.[](val); super.downcase; end => nil >> h["a"] = "ABC" => "ABC" >> h["a"] # This gives you downcased string. => "abc" >> h.fetch("a") # But this doesn't. => "ABC" >> h.values # Neither does this. => ["ABC"] I think also that Paul is dealing with a hash that already has some values, so the iterative solutions might be better. David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!