Home > other >  Difference bw puts with braces() and without braces
Difference bw puts with braces() and without braces

Time:10-08

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 to true and then is used as an argument to puts (which returns nil);
  • in the second example puts("odin") returns nil which is then evaluated to true in nil || 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

  • Related