‘||’ unequal ‘or’

Posted by crux on October 21, 2007

some simple ruby code:

a = nil || 23
b = nil or 23
puts "#{a==b}"
prints: false. Please explain! I mean explain in the sense of why not how it happens. Is it meaningful to put ‘||’ and ‘or’ on a different level in the precedence hierarchy?

UPDATE: i checked a couple of times before i posted but still can’t reproduce it a day later. don’t know what was different yesterday, Jruby? confused, … i seem that puts "#{a == b}" prints true. today.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Etapeta Mon, 22 Oct 2007 11:42:04 BST

    I have the same behaviour. It must depend on operators’ precedence.

    While a = nil || 23 gets interpreted as we imagine, b = nil or 23 gets interpreted as (b = nil) or 23

  2. schmidt Mon, 22 Oct 2007 11:57:24 BST

    No, it should not print true. Neither should jruby or any other interpreter. “=” has a higher precedence than “or” so your statement should always read “(b = nil) or 23″, which is always “23″ and always assigns “nil” to “b”.

    I have thought a while about a possible use case and could not come up with one, but I guess it will look like a long logical expression with lots of paranthesis, which may be written with less paranthesis, when regarding the operator precedence.

    (not true && false) #=> true b = (not true and false) #=> false

    This difference could actually make sense in a logical expression

  3. or^3 « mediapeers DevBlog Wed, 14 May 2008 15:01:41 BST

    [...] A nice one on Ruby operator precedence found at Dirk’s. [...]

Comments