I’ve seen this code in a rails tutorial I’m doing
def access_denied
redirect_to login_path, :notice => "Please log in to continue" and return false
end
Before learning rails, I did a large amount of ruby research and none of the books I read covered this “and return false” syntax going on here. I can’t find any mention of it in the rails syntax, is anyone able to provide a link or any explanation that would clear this up?
I don’t understand the need for the “and” in here as I thought ruby would always return the last evaluated expression.
The and is there only for you to be able to write the return false at the same line as the previous statement.
It’s equivalent of doing this:
it’s not exactly the same because with the “and” it would only return false if the redirect_to method returns something that isn’t nil or false but as it almost always returns something that is not nil nor false then the right side of the statement is always executed (and false is returned).
The and in Ruby is just an alias to && and behaves exactly like it with only one difference, it has a lower precedence than all other pieces of the statement, so first it evaluates whatever is on it’s left and then gets applied. Ruby also has the or which is the same as || but with a lower precedence in expressions.