From: James Herdman Date: 2008-11-10T23:34:49+09:00 Subject: Re: replace values in hash ------=_Part_86851_21105454.1226327832499 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit Content-Disposition: inline Not bad. Let's tighten it up a little: class Hash def replace_value(old, new) self.inject({}) do |result, (key, existing_value)| result[key] = (value == old) ? new : existing_value result end end end This isn't bad, but you wouldn't want to do this for large Hashes since you end up copying the original. James On Wed, Nov 5, 2008 at 12:38 PM, Brian Adkins wrote: > Jason Lillywhite writes: > > > how would I iterate over a hash, such as > > > > x = { 'a' => "hi", 'b' => nil, 'c' => "do"} > > > > and replace nil values with 'foo' then return the hash again? > > ~/temp$ cat -b temp.rb > 1 require 'pp' > > 2 class Hash > 3 def replace_value old, new > 4 self.inject({}) do |result,pair| > 5 k, v = pair[0], pair[1] > 6 result[k] = (v == old) ? new : v > 7 result > 8 end > 9 end > 10 end > > 11 x = { 'a' => "hi", 'b' => nil, 'c' => "do", :d => nil } > 12 pp x > 13 y = x.replace_value(nil, 'foo') > 14 pp y > ~/temp$ ruby temp.rb > {"a"=>"hi", "b"=>nil, :d=>nil, "c"=>"do"} > {"a"=>"hi", "b"=>"foo", "c"=>"do", :d=>"foo"} > > -- > Brian Adkins > http://www.lojic.com/ > http://lojic.com/blog/ > > ------=_Part_86851_21105454.1226327832499--