三元运算符Ruby put

时间:2015-10-22 21:15:11

标签: ruby

我不明白为什么以下声明提出:     “一个不到两个!”到了屏幕而不是直接放在puts之前的代码?

以下是声明:

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

有人可以解释原因吗?

2 个答案:

答案 0 :(得分:2)

您的问题的答案是the ternary operator has higher precedence than the method call*的优先级高于+,因此在将结果传递给方法之前评估三元表达式。

换句话说,这个:

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

..相当于:

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

..和这个:

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

答案 1 :(得分:1)

问号的左侧需要是真还是假。如果它是真的,它将执行结肠的左侧。如果为false,则执行右侧。所以它应该是:

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