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

本文翻译自:How do I use the conditional operator (? :) in Ruby?

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 %>

#1楼

参考:https://stackoom.com/question/hQnK/如何在Ruby中使用条件运算符


#2楼

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. 我发现了一个关于这个话题的帖子 ,看起来很有帮助。


#3楼

It is the ternary operator , and it works like in C (the parenthesis are not required). 它是三元运算符 ,它的工作方式与C类似(不需要括号)。 It's an expression that works like: 这是一个表达式,如下所示:

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 但是,在Ruby中, if也是一个表达式: if a then b else c end === a ? b : c a ? b : c , except for precedence issues. a ? b : c ,除了优先级问题。 Both are expressions. 两者都是表达。

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会混淆,因为它认为它是puts if 1有一些额外的垃圾),但在最后一种情况下它们不是必需的,因为不会出现所述问题。

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

#4楼

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


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

#5楼

@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会引发错误,但您可以在行的末尾使用\\ line-continuation符号,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: 通过将运算符放在最后一行,也可以使用没有行继续符号的三元组,但我不喜欢或推荐它:

(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. 如果使用得当它们很强大,所以我们应该学会正确使用它们。


Why have you put brackets around true ? 为什么你把括号括为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. 很容易认为可读性在question.question也会受到严重影响。 question.question也是如此。


#6楼

Your use of ERB suggests that you are in Rails. 您对ERB的使用表明您使用的是Rails。 If so, then consider truncate , a built-in helper which will do the job for you: 如果是这样,那么考虑truncate ,一个内置的帮助器,它将为您完成这项工作:

<% question = truncate(question, :length=>30) %>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值