Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Ruby 1.9.2 give a syntax error for: puts(true and false)?

Tags:

ruby

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

like image 780
Felix Rabe Avatar asked Oct 08 '22 11:10

Felix Rabe


2 Answers

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)
like image 130
nolith Avatar answered Oct 12 '22 12:10

nolith


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

like image 37
Thilo Avatar answered Oct 12 '22 10:10

Thilo