Search code examples
rubyternary

Ruby ternary operator structure


puts bool ? "true" : "false"

is proper, but

bool ? puts "true" : puts "false"

is not. Can somebody explain to me why this is?

Side note:

bool ? ( puts "true" ) : ( puts "false" )

works fine as well.


Solution

  • When you don't put the parentheses on a method call, Ruby assumes you want everything to the end of the line to be the arguments. That is to say, these calls are equivalent (and invalid):

    bool ? puts "true" : puts "false"
    bool ? puts("true" : puts "false")