1

What is the difference bw puts("Odin") and puts "Odin"?
Context
puts "odin" || true gives different result than puts("odin") || true

potashin
  • 44,205
  • 11
  • 83
  • 107
koil
  • 41
  • 4

3 Answers3

3

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.

spickermann
  • 100,941
  • 9
  • 101
  • 131
2

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;
potashin
  • 44,205
  • 11
  • 83
  • 107
1

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

Haumer
  • 460
  • 4
  • 15