What is the difference bw puts("Odin") and puts "Odin"?
Context
puts "odin" || true
gives different result than puts("odin") || true
CodePudding user response:
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.
CodePudding user response:
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;
CodePudding user response:
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 where the braces are interpreted:
# for your first example these are equivalent:
puts "odin" || true #=> nil
puts("odin" || true) #=> nil
# for the second
puts("odin") || true #=> true
Note that puts returns nil so its evaluating nil || true
which is true