Forum: Ruby Getting different results using Ruby IRB and files on method merge/code block

Posted by C. da Silva (cdasilva)
on 2012-09-28 22:18
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 result as the second
script (and I know the results on second script and irb are correct). Am
I missing something on the first script? Thanks.

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}
Posted by unknown (Guest)
on 2012-09-29 00:56
(Received via mailing list)
Am 28.09.2012 22:18, schrieb Carlos da Silva:
>
> # second script -- Results: {"n1"=>0, "n2"=>44, "n3"=>88}
>
> puts h1.merge(h2) {|key,old,new| old < new ? old : new}

Seems to be a precedence issue:

first example behaves like     puts(h1.merge(h2))  do ... end
second example behaves like    puts(h1.merge(h2) {...})

It has nothing to do with the block itself, this works fine:

merged = h1.merge(h2) do |...|
            ...
          end
puts merged
Posted by C. da Silva (cdasilva)
on 2012-09-29 01:49
Thanks. it makes sense.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.