When I run these two Ruby scripts I got two different answers. Also, if I run the first script on irb, I get the same results as the second script (and I know the results on second script and irb are correct). Am I missing any anything on the first script? Thanks for the help.
Ruby version: 1.9.3
Text Editor: TextWrangler
h1 = {"n1"=> 00, "n2"=> 44}
h2 = {"n2"=> 66, "n3"=> 88}
first script — Results: {"n1"=>0, "n2"=>66, "n3"=>88}
puts h1.merge(h2) do |key, old, new|
if old < new
old
else
new
end
end
second script — Results: {"n1"=>0, "n2"=>44, "n3"=>88}
puts h1.merge(h2) {|key,old,new| old < new ? old : new}
In the first case Ruby thinks block belongs to
puts, not tomerge, use{}:UPDATE: You can find details in the Programming Ruby book.