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/