I am puzzled that Ruby 1.9 (JRuby 1.6.6 (RUBY_VERSION == “1.9.2”) and Ruby 1.9.3-p125) give a syntax error for puts(true and false).
I don’t know why – what is the problem here? How would I write that piece of code correctly? puts(true && false) works but is there a solution with and?
Example irb session:
1.9.3p125 :001 > puts(true and false)
SyntaxError: (irb):1: syntax error, unexpected keyword_and, expecting ')'
puts(true and false)
^
from /home/fr/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'
1.9.3p125 :002 > puts(true && false)
false
=> nil
Thanks to Mladen Jablanović for simplifying the example. The old example was f(true and f(false)).
The operator precedence in ruby is
&&before=beforeand. So in your example usingand, it would try to make this (implicit) assignment:and then combine it with
via
and, which causes the syntax error. See a great explanation here: Difference between "and" and && in Ruby?EDIT: I’m not sure if my “implicit assignment” makes sense – think of this statement to make it explicit:
EDIT 2: Remember that a method call is really called on an object. So the equivalent statements for the two cases would be:
Not sure if that helps any more – you’re right, it’s a bit counter-intuitive. My solution is to stay away from
and🙂