Monday, 18 March 2013

ruby operator precedence explained with an example

OR has lower precence than ||, in particular assignments (=) are in the middle, therefor:
a = false || true # => true
a                 # => **true**  => a = (false || true)
# BUT
a = false or true # => true
a                 # => **false** => (a = false) or true

# another BIG difference
:a || :b && :c  # => :a          => (:a || :b) && :c
# BUT 
:a or :b and :c # => **c**       => :a or (:b and :c)


Got it?
Where does it make sense to use the English operators?
a = value or raise "a cannot be nil"

def tail_color(args)
  animal = args[:animal] and
  tail = animal.tail and
  tail.color
end


Conclusion: only use English operators for flow control, not in if statements
also see this table