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.
When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number. If the value is omitted, undefined is returned instead.
Is it possible to write return statement in if block? It is possible, but you haven't covered all the possible cases to which the program flow may go.
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
Return statement in catch will be executed only if the catch block is reached, i.e. if there is an error thrown. example() will return 2 since an error was thrown before return 1 . But if there is a finally block and this finally block has a return statement then this return will override catch return statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With