如何使用条件运算符(?:在Ruby)?

时间:2021-10-15 22:25:09

How is the conditional operator (? :) used in Ruby?

条件运算符是怎样的?:)中使用Ruby ?

For example, is this correct?

例如,这是正确的吗?

<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>

6 个解决方案

#1


375  

It is the ternary operator, and it works like in C (the parenthesis are not required). It's an expression that works like:

它是三元运算符,它的工作方式类似于C(不需要括号)。它的表达方式是:

if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this

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.

然而,在Ruby中,if也是一个表达式:if a then b else c end == a ?b: c,除了优先问题。都是表情。

Examples:

例子:

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

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.

请注意,在第一个案例中,括号是必需的(否则Ruby会被混淆,因为它认为如果有一些额外的垃圾,它会被放入其中),但是在最后一个案例中,它们并不是必需的,因为这个问题不会出现。

You can use the "long-if" form for readability on multiple lines:

您可以在多行中使用“long-if”形式的可读性:

question = if question.size > 20 then
  question.slice(0, 20) + "..."
else 
  question
end

#2


27  

puts true ? "true" : "false"
=> "true"


puts false ? "true" : "false"
=> "false"

#3


23  

Your use of ERB suggests that you are in Rails. If so, then consider truncate, a built-in helper which will do the job for you:

你对ERB的使用表明你在Rails中。如果是这样,那么考虑truncate,一个内置的帮助器,它将为您完成工作:

<% question = truncate(question, :length=>30) %>

#4


15  

@pst gave a great answer, but I'd like to mention that in Ruby the ternary operator is written on one line to be syntactically correct, unlike Perl and C where we can write it on multiple lines:

@pst给出了一个很好的答案,但我想说的是,在Ruby中,三元运算符是在一行上写的,是语法正确的,不像Perl和C,我们可以把它写在多行上:

(true) ? 1 : 0

Normally Ruby will raise an error if you attempt to split it across multiple lines, but you can use the \ line-continuation symbol at the end of a line and Ruby will be happy:

如果您试图跨多个行分割它,通常Ruby会产生一个错误,但是您可以在一行的末尾使用\行延续符号,而Ruby将会很高兴:

(true)   \
  ? 1    \
  : 0

This is a simple example, but it can be very useful when dealing with longer lines as it keeps the code nicely laid out.

这是一个简单的例子,但是它在处理较长的行时非常有用,因为它可以很好地显示代码。

It's also possible to use the ternary without the line-continuation characters by putting the operators last on the line, but I don't like or recommend it:

也可以使用ternary而不使用行延续字符,将操作符放在最后一行,但我不喜欢或推荐它:

(true) ?
  1 :
  0

I think that leads to really hard to read code as the conditional test and/or results get longer.

我认为这会导致很难读懂代码,因为条件测试和/或结果会变长。

I've read comments saying not to use the ternary operator because it's confusing, but that is a bad reason to not use something. By the same logic we shouldn't use regular expressions, range operators ('..' and the seemingly unknown "flip-flop" variation). They're powerful when used correctly, so we should learn to use them correctly.

我读过一些评论,说不要使用三元运算符,因为它令人困惑,但这是不使用的一个坏理由。按照同样的逻辑,我们不应该使用正则表达式,range运算符(……还有看似不为人知的“触发器”变体。当使用正确时,它们是强大的,所以我们应该学会正确使用它们。


Why have you put brackets around true?

你为什么把括号括起来?

Consider the OP's example:

考虑OP的例子:

<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>

Wrapping the conditional test helps make it more readable because it visually separates the test:

对条件测试进行包装有助于使其更具可读性,因为它可以在视觉上区分测试:

<% question = (question.size > 20) ? question.question.slice(0, 20)+"..." : question.question %>

Of course, the whole example could be made a lot more readable by using some judicious additions of whitespace. This is untested but you'll get the idea:

当然,通过使用一些明智的增补空格,可以使整个示例更具可读性。这是未经测试的,但你会知道:

<% question = (question.size > 20) ? question.question.slice(0, 20) + "..." \
                                   : question.question 
%>

Or, more written more idiomatically:

或者,写得更地道一些:

<% question = if (question.size > 20)
                question.question.slice(0, 20) + "..."
              else 
                question.question 
              end
%>

It'd be easy to argument that readability suffers badly from question.question too.

人们很容易认为可读性受到了严重的质疑。问题。

#5


3  

A simple example where the operator checks if player's id is 1 and sets enemy id depending on the result

一个简单的例子,操作员检查玩家的id是否为1,并根据结果设置敌人的id。

player_id=1
....
player_id==1? enemy_id=2 : enemy_id=1
# => enemy=2

And I found a post about to the topic which seems pretty helpful.

我找到了一个关于这个话题的帖子,似乎很有帮助。

#6


0  

One small variation of this is to use the convert to boolean !! operator like this

其中一个小的变化是使用转换为布尔!!这样的运营商

result = !!(condition == true)

#1


375  

It is the ternary operator, and it works like in C (the parenthesis are not required). It's an expression that works like:

它是三元运算符,它的工作方式类似于C(不需要括号)。它的表达方式是:

if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this

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.

然而,在Ruby中,if也是一个表达式:if a then b else c end == a ?b: c,除了优先问题。都是表情。

Examples:

例子:

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

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.

请注意,在第一个案例中,括号是必需的(否则Ruby会被混淆,因为它认为如果有一些额外的垃圾,它会被放入其中),但是在最后一个案例中,它们并不是必需的,因为这个问题不会出现。

You can use the "long-if" form for readability on multiple lines:

您可以在多行中使用“long-if”形式的可读性:

question = if question.size > 20 then
  question.slice(0, 20) + "..."
else 
  question
end

#2


27  

puts true ? "true" : "false"
=> "true"


puts false ? "true" : "false"
=> "false"

#3


23  

Your use of ERB suggests that you are in Rails. If so, then consider truncate, a built-in helper which will do the job for you:

你对ERB的使用表明你在Rails中。如果是这样,那么考虑truncate,一个内置的帮助器,它将为您完成工作:

<% question = truncate(question, :length=>30) %>

#4


15  

@pst gave a great answer, but I'd like to mention that in Ruby the ternary operator is written on one line to be syntactically correct, unlike Perl and C where we can write it on multiple lines:

@pst给出了一个很好的答案,但我想说的是,在Ruby中,三元运算符是在一行上写的,是语法正确的,不像Perl和C,我们可以把它写在多行上:

(true) ? 1 : 0

Normally Ruby will raise an error if you attempt to split it across multiple lines, but you can use the \ line-continuation symbol at the end of a line and Ruby will be happy:

如果您试图跨多个行分割它,通常Ruby会产生一个错误,但是您可以在一行的末尾使用\行延续符号,而Ruby将会很高兴:

(true)   \
  ? 1    \
  : 0

This is a simple example, but it can be very useful when dealing with longer lines as it keeps the code nicely laid out.

这是一个简单的例子,但是它在处理较长的行时非常有用,因为它可以很好地显示代码。

It's also possible to use the ternary without the line-continuation characters by putting the operators last on the line, but I don't like or recommend it:

也可以使用ternary而不使用行延续字符,将操作符放在最后一行,但我不喜欢或推荐它:

(true) ?
  1 :
  0

I think that leads to really hard to read code as the conditional test and/or results get longer.

我认为这会导致很难读懂代码,因为条件测试和/或结果会变长。

I've read comments saying not to use the ternary operator because it's confusing, but that is a bad reason to not use something. By the same logic we shouldn't use regular expressions, range operators ('..' and the seemingly unknown "flip-flop" variation). They're powerful when used correctly, so we should learn to use them correctly.

我读过一些评论,说不要使用三元运算符,因为它令人困惑,但这是不使用的一个坏理由。按照同样的逻辑,我们不应该使用正则表达式,range运算符(……还有看似不为人知的“触发器”变体。当使用正确时,它们是强大的,所以我们应该学会正确使用它们。


Why have you put brackets around true?

你为什么把括号括起来?

Consider the OP's example:

考虑OP的例子:

<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>

Wrapping the conditional test helps make it more readable because it visually separates the test:

对条件测试进行包装有助于使其更具可读性,因为它可以在视觉上区分测试:

<% question = (question.size > 20) ? question.question.slice(0, 20)+"..." : question.question %>

Of course, the whole example could be made a lot more readable by using some judicious additions of whitespace. This is untested but you'll get the idea:

当然,通过使用一些明智的增补空格,可以使整个示例更具可读性。这是未经测试的,但你会知道:

<% question = (question.size > 20) ? question.question.slice(0, 20) + "..." \
                                   : question.question 
%>

Or, more written more idiomatically:

或者,写得更地道一些:

<% question = if (question.size > 20)
                question.question.slice(0, 20) + "..."
              else 
                question.question 
              end
%>

It'd be easy to argument that readability suffers badly from question.question too.

人们很容易认为可读性受到了严重的质疑。问题。

#5


3  

A simple example where the operator checks if player's id is 1 and sets enemy id depending on the result

一个简单的例子,操作员检查玩家的id是否为1,并根据结果设置敌人的id。

player_id=1
....
player_id==1? enemy_id=2 : enemy_id=1
# => enemy=2

And I found a post about to the topic which seems pretty helpful.

我找到了一个关于这个话题的帖子,似乎很有帮助。

#6


0  

One small variation of this is to use the convert to boolean !! operator like this

其中一个小的变化是使用转换为布尔!!这样的运营商

result = !!(condition == true)