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

发布于 2024-10-04 10:02:21 字数 190 浏览 9 评论 0原文

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

例如,这是正确的吗?

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

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

For example, is this correct?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

梦开始←不甜 2024-10-11 10:02:23
puts true ? "true" : "false"
=> "true"


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


puts false ? "true" : "false"
=> "false"
思念满溢 2024-10-11 10:02:23

您对 ERB 的使用表明您使用的是 Rails。如果是这样,请考虑截断 ,一个内置的助手,它将为您完成这项工作:

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

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:

<% question = truncate(question, :length=>30) %>
浮生未歇 2024-10-11 10:02:23

@pst 给出了一个很好的答案,但我想提一下,在 Ruby 中,三元运算符写在一行上,以便在语法上正确,这与 Perl 和 C 不同,我们可以将其写在多行上:

(true) ? 1 : 0

通常 Ruby 会在以下情况下引发错误 :您尝试将其拆分为多行,但您可以在行尾使用 \ 行继续符,Ruby 会很高兴:

(true)   \
  ? 1    \
  : 0

这是一个简单的示例,但它非常有用当处理较长的行时,因为它可以使代码保持良好的布局。

也可以通过将运算符放在行的最后来使用不带行连续字符的三元,但我不喜欢或推荐它:

(true) ?
  1 :
  0

我认为这会导致代码作为条件测试和/或结果很难阅读变得更长。

我读过评论说不要使用三元运算符,因为它很令人困惑,但这是不使用某些东西的糟糕理由。按照同样的逻辑,我们不应该使用正则表达式、范围运算符(“..”和看似未知的“触发器”变体)。正确使用它们会非常强大,所以我们应该学会正确使用它们。


为什么要在 true 两边加上括号?

考虑OP的示例:

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

包装条件测试有助于使其更具可读性,因为它在视觉上分隔了测试:

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

当然,通过使用一些明智的空白添加,可以使整个示例更具可读性。这尚未经过测试,但您会明白这个想法:

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

或者,更写得更惯用:

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

很容易争论 question.question 的可读性也受到严重影响。

@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:

(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:

(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?

Consider the OP's example:

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

泛滥成性 2024-10-11 10:02:23

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

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

我发现了一个 post 关于该主题,这似乎非常有帮助。

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

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.

月寒剑心 2024-10-11 10:02:23

最简单的方法:

param_a = 1
param_b = 2

result = param_a === param_b ? 'Same!' : 'Not same!'

由于param_a不等于param_b,那么结果的值将是不一样!

Easiest way:

param_a = 1
param_b = 2

result = param_a === param_b ? 'Same!' : 'Not same!'

since param_a is not equal to param_b then the result's value will be Not same!

请爱~陌生人 2024-10-11 10:02:23

代码条件? statements_A : statements_B 相当于

if condition == true
  statement_A
else
  statement_B
end

The code condition ? statement_A : statement_B is equivalent to

if condition == true
  statement_A
else
  statement_B
end
怪我鬧 2024-10-11 10:02:22

它是三元运算符,其工作方式与C 中类似(不需要括号)。这个表达式的工作原理如下:

if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this

然而,在 Ruby 中,if 也是一个表达式,因此: if a then b else c end === a ? b : c,优先级问题除外。两者都是表达。

示例:

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

您可以使用“long-if”形式来提高多行的可读性:

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

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

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.

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.

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文