简体   繁体   中英

Ternary operator Ruby puts

I don't understand why the following statement puts: "One is less than two!" to the screen instead of the code directly in front of puts?

Here's the statement:

X = 1 < 2 
puts X == true ? "One is less than two!" : "One is not less than two."

Can someone explain why?

The answer to your question is that the ternary operator has higher precedence than the method call , in the same way * has higher precedence than + , so the ternary expression is evaluated before its result is passed to the method.

In other words, this:

puts X == true ? "One is less than two!" : "One is not less than two."

..is equivalent to this:

puts(X == true ? "One is less than two!" : "One is not less than two.")

..and not this:

puts(X == true) ? "One is less than two!" : "One is not less than two."

The left side of the question mark needs to be true or false. If it's true, it'll execute the left side the the colon. If false, it'll execute the right side. So it should just be:

1 < 2 ? puts "One is less than two!" : puts "One is not less than two"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM