如何在 Ruby 中使用条件运算符 (? :)? [英] How do I use the conditional operator (? :) in Ruby?

查看:27
本文介绍了如何在 Ruby 中使用条件运算符 (? :)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如,这是正确的吗?

<% 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 中,if 也是一个表达式,所以: if a then 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 会感到困惑,因为它认为 puts if 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 中使用条件运算符 (? :)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆