gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:16:13 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com