How come (a_method || :other) returns :other only when assigning to a var called a_method?

Posted by Paul Annesley on Stack Overflow See other posts from Stack Overflow or by Paul Annesley
Published on 2011-01-13T09:28:09Z Indexed on 2011/01/13 9:53 UTC
Read the original article Hit count: 263

Filed under:

Given the following method:

def some_method
  :value
end

The following statements work as I would expect:

some_method || :other
# => :value

x = some_method || :other
# => :value

But the behaviour of the following statement perplexes me:

some_method = some_method || :other
# => :other

It creates a local variable called some_method as expected, and subsequent calls to some_method return the value of that local variable. But why does it assign :other rather than :value?

I understand that it's probably not a smart thing to do, and can see how it might be ambiguous, but I thought the right-hand-side of the assignment should be evaluated prior to the assignment being considered...

I've tested this in Ruby 1.8.7 and Ruby 1.9.2 with identical results.

Cheers!

Paul

© Stack Overflow or respective owner

Related posts about ruby