Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 350
pez_dispenser Avatar asked May 15 '09 03:05

pez_dispenser


People also ask

Can I use return in if statement?

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.

Can we write return statement in if block?

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.

What does return statement do in IF statement?

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.

What will happen if return statement is added in one of the catch block?

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.


1 Answers

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.

like image 52
Chuck Avatar answered Oct 06 '22 00:10

Chuck