5

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)).

Felix Rabe
  • 4,206
  • 4
  • 25
  • 34

2 Answers2

3

It's all about precedences "and" and "&&" does not have the same precedeces on operands, try using

f((true and f(false)))

'and' should be used for something like "do stuff A if this worked ok then do stuffs B" and not for strict boolean checking.

check_db(param) and connect_db(param)
nolith
  • 613
  • 6
  • 16
1

The operator precedence in ruby is && before = before and. So in your example using and, it would try to make this (implicit) assignment:

puts(true 

and then combine it with

false)

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:

foo = puts(true and false)

EDIT 2: Remember that a method call is really called on an object. So the equivalent statements for the two cases would be:

Object.send("puts", true && false) # this works
Object.send("puts", true and false) # this is a syntax error
Object.send("puts", (true and false)) # works again

Not sure if that helps any more - you're right, it's a bit counter-intuitive. My solution is to stay away from and :)

Community
  • 1
  • 1
Thilo
  • 17,565
  • 5
  • 68
  • 84
  • 1
    That is so counter-intuitive to me. This implies that `and` has lower precedence than method argument parentheses. Is this just a bug in Ruby or is there a concept behind this that I just don't get yet? – Felix Rabe Mar 08 '12 at 11:15