Why does this method return 1 rather than dying from infinite recursion?
def foo
foo ||= 1
end
foo # => 1
Rewritten the following way it does die:
def foo
foo.nil? ? 1 : foo
end
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In the first case,
foo ||= 1refers to a local variable. Ruby always creates a local variable when you do assignment on a bareword, which is why you have to writeself.foo = ...if you want to invoke a writer method defined asdef foo=(value). The||=operator is, after all, just a fancy assignment operator.In the second case, there is no assignment, so when it hits
foo.nil?, Ruby interprets the barewordfooas a method call, and blows up.