The keyword and
has lower precedence than &&
. Both use short-circuit evaluation.
First, note that puts
always returns nil
. In ruby, nil
is falsey.
2.2.0 :002 > puts "asdf"
asdf
=> nil
Now we try your example:
2.2.0 :002 > puts "asd" and puts "xxx"
asd
=> nil
This is the same as:
puts("asd") && puts("xxx")
asd
=> nil
In both cases puts "asd"
and puts("asd")
return nil
so puts "xxx"
and puts("xxx")
are never evaulated because nil
is falsey and there is short-circuit evaulation being used.
You also tried puts "asd" && puts "xxx"
, but this is a syntax error because of the higher precendence of the &&
operator.
puts "asd" && puts "xxx"
SyntaxError: (irb):3: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
puts "asd" && puts "xxx"
^
That's because puts "asd" && puts "xxx"
is the same as puts("asd" && puts) "xxx"
.
2.2.0 :012 > puts("asd" && puts) "xxx"
SyntaxError: (irb):12: syntax error, unexpected tSTRING_BEG, expecting end-of-input
puts("asd" && puts) "xxx"
^
See also: this related post