Reputation: 1290
In Ruby an explicit return inside a method is normally placed before an expression and returns the value of that expression, like in the code below:
def method_with_explicit_return
:a_non_return_value
return :return_value
:another_non_return_value
end
assert_equal :return_value, method_with_explicit_return
Unless a conditional is used and evaluated (like in return :return_value unless a < b
), any piece of code that comes after the return expression is ignored.
In Ruby on Rails I came across the following expression inside a controller action:
redirect_to root_url and return
Why return
is placed at the end of the redirect_to
expression and what is its function?
Upvotes: 0
Views: 307
Reputation: 430
In Rails, redirect_to
will not return from the method but only sets up headers for the response. You have to explicitly return for it to stop execution and proceed with the response. You can also write that code like,
return redirect_to root_url
Upvotes: 2