问题描述
在Ruby中如何使用条件运算符(?:
)?
How is the conditional operator (? :
) used in Ruby?
例如,这是正确的吗? ?
For example, is this correct?
<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>
推荐答案
它是,其工作方式类似于C语言(不需要括号)。该表达式的工作方式如下:
It is the ternary operator, and it works like in C (the parenthesis are not required). It's an expression that works like:
if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this
但是,在Ruby中,如果 >也是一个表达式,因此:
如果a然后b else c end
=== a? b:c
,优先级问题除外。
However, in Ruby,
if
is also an expression so: if a then b else c end
=== a ? b : c
, except for precedence issues. Both are expressions.
示例:
puts (if 1 then 2 else 3 end) # => 2
puts 1 ? 2 : 3 # => 2
x = if 1 then 2 else 3 end
puts x # => 2
请注意,在第一种情况下,必须使用括号(否则Ruby会感到困惑,因为它认为
放入1
,然后加上一些垃圾),但在最后一种情况下则不需要,因为不会出现上述问题。
Note that in the first case parenthesis are required (otherwise Ruby is confused because it thinks it is
puts if 1
with some extra junk after it), but they are not required in the last case as said issue does not arise.
您可以在多行中使用 long-if格式以提高可读性:
You can use the "long-if" form for readability on multiple lines:
question = if question.size > 20 then
question.slice(0, 20) + "..."
else
question
end
这篇关于如何在Ruby中使用条件运算符(?:)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!