ruby - 是三元运算符? : defined as a method in Ruby?

标签 ruby ternary-operator

我是 Ruby 的新手,对三元运算符 ?: 的工作原理有点困惑。

据书Engineering Software as a Service: An Agile Approach Using Cloud Computing :

every operation is a method call on some object and returns a value.

从这个意义上说,如果三元运算符表示一个操作,那么它就是对具有两个参数的对象的方法调用。但是,我在 Ruby's documentation 中找不到三元运算符代表的任何方法。 .三元运算符是否表示 Ruby 中的操作?书中提到的上述说法是错误的吗? Ruby 中的三元运算符真的只是 if ... then ... else ... end 语句的语法糖吗?

请注意: 我的问题与 How do I use the conditional operator (? :) in Ruby? 有关但和那个不一样。我知道如何按照该帖子中描述的方式使用三元运算符。我的问题是关于三元运算符在 Ruby 中的何处定义以及三元运算符是否被定义为一个或多个方法。

最佳答案

Is the ternary operator in Ruby really just a syntactic sugar for if ... then ... else ... end statements?

是的。

来自 doc/syntax/control_expressions.rdoc

You may also write a if-then-else expression using ? and :. This ternary if:

input_type = gets =~ /hello/i ? "greeting" : "other"

Is the same as this if expression:

input_type =
  if gets =~ /hello/i
    "greeting"
  else
    "other"
  end

"According to this book, "every operation is a method call on some object and returns a value." In this sense, if the ternary operator represents an operation, it is a method call on an object with two arguments."

ifunlesswhileuntil 不是运算符,它们是控制结构。它们的修饰符版本出现在 operator precedence table 中因为它们需要有优先级才能被解析。他们只是检查他们的条件是真还是假。在 Ruby 中这很简单,只有 falsenil 是 false。其他一切都是真实的。

运算符是 !+*[]。他们是unarybinary .您可以通过对各种对象调用 .methods.sort 来查看它们的列表。例如……

2.4.3 :004 > 1.methods.sort
 => [:!, :!=, :!~, :%, :&, :*, :**, :+, :+@, :-, :-@, :/, :<, :<<, :<=, :<=>, :==, :===, :=~, :>, :>=, :>>, :[], :^, :__id__, :__send__, etc...

请注意,在 Smalltalk 中,Ruby 大量借鉴,一切都是方法调用。 Including the control structures .

关于ruby - 是三元运算符? : defined as a method in Ruby?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52022945/

相关文章:

mysql - 使用 MySQL 在 Rails 中对长文本进行分页

ruby - .each 看似递归到二维数组的第二维

Java语句: Obfuscated code - `?:`

c - 三元运算符翻译

ruby - 检查文件是否是有效图像

html - 如何根据位置使用 watir 从 ruby​​ 中的文本文件中读取值

ruby - 文件/文件夹名称的字符过滤器无效? ( ruby )

for语句中的比较运算符

javascript - 需要AngularJS/Javascript三元运算符代码解释

PHP 创建一个新对象还是使用现有对象(如果已设置)?