1

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

1 Answer 1

4

In the first case, foo ||= 1 refers to a local variable. Ruby always creates a local variable when you do assignment on a bareword, which is why you have to write self.foo = ... if you want to invoke a writer method defined as def 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 bareword foo as a method call, and blows up.

Sign up to request clarification or add additional context in comments.

3 Comments

Why in the first case and not the second?
OK, I think it is because in the first case, the ||= is seen by the interpreter first as an assignment rather than as the condition nil?, which makes it interpreted as a local variable rather than a method. -- I see you've added the same explanation.
Yep, that's it, I updated my answer. This site explains it in some detail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.