What is the difference bw puts("Odin") and puts "Odin"?
Context
puts "odin" || true
gives different result than puts("odin") || true
3 Answers
Ruby understands puts "odin" || true
as puts("odin" || true)
which will always output odin
. It will not evaluate the || true
part because "odin"
is already truthy. And that line will return nil
because that is the default return value of the puts
method.
puts("odin") || true
will output odin
too but will return true
because the return value of puts("odin")
is nil
and therefore the || true
will be evaluated and the true
will be returned.

- 100,941
- 9
- 101
- 131
The difference is in the priority of evaluation:
- in the first example
"odin" || true
evaluates totrue
and then is used as an argument toputs
(which returnsnil
); - in the second example
puts("odin")
returnsnil
which is then evaluated totrue
innil || true
statement;

- 44,205
- 11
- 83
- 107
braces are optional in ruby, or better said: in some cases spaces act as like braces would.
the reason you get two different results is because of where the braces are interpreted, so both the following statements print "odin" and return nil:
puts "odin" || true
puts("odin" || true)
Remember here that strings are truthy in ruby, meaning we actually have a condition inside the puts method, ie true || false #=> true
As for the second example, the condition is no longer passed as a argument to the puts method. puts returns nil, which is falsey.
puts("odin") || true #=> true
this means the overall return is nil || true #=> true

- 460
- 4
- 15