‘||’ unequal ‘or’
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.
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
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
[...] A nice one on Ruby operator precedence found at Dirk’s. [...]