0

When I evaluate the expression a = nil || 2008 in Irb, I get the answer as 2008 and a is assigned the value 2008 which is correct as || operator return their first argument unless it is false or nil.

But when I do something like a = nil or 2008 on Irb console, a is assigned nil and the return value of the evaluation of the expression I get is still 2008.

Has it got something to do with operator precedence. I was just wondering why it works this way, can someone please shed some light on this ?

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
MegaChief
  • 7
  • 3

3 Answers3

5

|| and or have different precedences. This was meant to be used, e.g. for error handling:

foo = do_something_which_could_fail_and_return_nil_then(...) or deal_with_error(...)

Some people think it should be avoided, i.e. or and and should not be used at all.

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
4

Order of precedence in your cases is following(from higher to lower):

  1. ||
  2. =
  3. or

So here a = nil || 2008

  • Operation 1: nil || 2008
  • Operation 2: a = Operation 1

and for a = nil or 2008

  • Operation 1: a = nil
  • Operation 2: Operation 1 or 2008 which returns 2008, because Operation 1 is nil
Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
3

You answered it yourself. It is due to operator precedence. || has higher precedence then = and "or" has lower precedence then '='. Here is a precedence table for ruby operators

if you use

a = (nil or 2008)

then it will give same result as

a = nil || 2008
Qaisar Nadeem
  • 2,404
  • 13
  • 23