Why doesn't "puts(4 or 5)" work?

The following code works:

puts(4 || 5)

It prints “4”, as expected. But when I write…

puts(4 or 5)

…Ruby complains about some syntax error.

Why? I thought the only difference between “||” and “or” is their
precedence!

The difference is that “or” is a keyword rather than an operator. It
seems the Ruby parser doesn’t allow it in some contexts. For example,
you cannot write

[4 or 5]
{:x => 4 or 5}

But “puts (4 or 5)” works as expected.

Anyway, I think the logical keywords aren’t actually meant to be used
outside of boolean expressions. If we want to do tricks, we’re probably
supposed to use the operators.

That’s why there’s an “||=” operator but no “or=”. :wink:

Jan E. wrote in post #1051457:

The difference is that “or” is a keyword rather than an operator. It
seems the Ruby parser doesn’t allow it in some contexts. For example,
you cannot write

[4 or 5]
{:x => 4 or 5}

But “puts (4 or 5)” works as expected.

That’s probably parsed the same way as

puts((4 or 5))

Anyway, I think the logical keywords aren’t actually meant to be used
outside of boolean expressions. If we want to do tricks, we’re probably
supposed to use the operators.

That’s why there’s an “||=” operator but no “or=”. :wink:

:slight_smile:

Cheers

robert

Anyway, I think the logical keywords aren’t actually meant to be used
outside of boolean expressions. If we want to do tricks, we’re probably
supposed to use the operators.

They’re usually used for control flow, since they have such low
precedence:

some_method or puts “not true!”

This has always annoyed me until I decided to stop using “and” and “or”.

It is easier to use things in a way which do not surprise me ever and ||
and && have not surprised me yet.