pez_dispenser
pez_dispenser

Reputation: 4464

Why does the return keyword cause problems in my 'if block'?

The following code works fine:

person = {:a=>:A, :b=>:B, :c=>:C}
berson = {:a=>:A1, :b=>:B1, :c=>:C1}

kerson = person.merge(berson) do | key, oldv, newv |
if key == :a
  oldv
elsif key == :b
  newv
else
  key
end
end

puts kerson.inspect

but if I add return inside the "if block", I get an error:

person = {:a=>:A, :b=>:B, :c=>:C}
berson = {:a=>:A1, :b=>:B1, :c=>:C1}

kerson = person.merge(berson) do | key, oldv, newv |
if key == :a
  return oldv
elsif key == :b
  return newv
else
  return key
end
end

puts kerson.inspect

The error from the above code is:

unexpected return (LocalJumpError)

Can anyone explain this? I thought return could be optionally used wherever there is already the assumption of a value being returned.

Upvotes: 5

Views: 649

Answers (1)

Chuck
Chuck

Reputation: 237060

The reason for the error is that blocks don't really have their own scope that they return from — a return from a block is equivalent to returning from the surrounding method. What is the surrounding method here? There is none — it's at the top level, so it's equivalent to doing ruby -e "return", which will give you the same error. If you stick this inside a method, it will make the method return the value of the first branch of the if-clause that gets executed.

Upvotes: 12

Related Questions