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
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.