Precedence
Ruby's parser relies on a precedence table. In your example, or
has higher precedence than and
. Additionally, short-circuit evaluation won't evaluate the second term of an or-condition if the first expression is truthy.
Also, note that in Ruby Kernel#puts is a method that takes optional arguments, while if
is a lexical token. While many people omit parentheses in idiomatic Ruby, precedence can change what the parser sees when it evaluates a complex or ambiguous expression like true or true and false
. As you will see below, the distinction between a conditional and a method complicates matters further.
In general, one should parenthesize expressions to avoid ambiguity, and rely on operator precedence as little as possible. There are always exceptions, especially in expressive languages like Ruby, but as a rule of thumb it can simplify a Rubyist's life immensely.
Examine the Parser
If you are ever in doubt about what the parser sees, you don't have to rely on reasoning alone. You can use the Ripper module to examine the symbolic expression tree. For example:
require 'pp'
require 'ripper'
pp Ripper.sexp 'true or true and false'
This will show you:
[:program,
[[:binary,
[:binary,
[:var_ref, [:@kw, "true", [1, 0]]],
:or,
[:var_ref, [:@kw, "true", [1, 8]]]],
:and,
[:var_ref, [:@kw, "false", [1, 17]]]]]]
This shows that the parser thinks the expression, on its own, evaluates as if you'd parenthesized it as (true or true) and false
.
Likewise, an if-statement has the same precedence applied:
pp Ripper.sexp 'if true or true and false; end'
[:program,
[[:if,
[:binary,
[:binary,
[:var_ref, [:@kw, "true", [1, 3]]],
:or,
[:var_ref, [:@kw, "true", [1, 11]]]],
:and,
[:var_ref, [:@kw, "false", [1, 20]]]],
[[:void_stmt]],
nil]]]
However, because puts
is a method, it is parsed differently:
pp Ripper.sexp 'puts true or true and false'
[:program,
[[:binary,
[:binary,
[:command,
[:@ident, "puts", [1, 0]],
[:args_add_block, [[:var_ref, [:@kw, "true", [1, 5]]]], false]],
:or,
[:var_ref, [:@kw, "true", [1, 13]]]],
:and,
[:var_ref, [:@kw, "false", [1, 22]]]]]]
In other words, the parser assumes your ambiguous statement is roughly equivalent to the following parenthesized expressions: (puts(true) or true) and (false)
. In this case, the first true
was assumed to be an argument to Kernel#puts. Since the puts method always returns nil
(which is falsey), the second true
is then evaluated, making puts(true) or true
truthy. Next, the terminal expression is evaluated and returns false
, regardless of the fact that the puts-statement prints true
to standard output.