当我们在 ruby​​ 中使用运算符时会发生什么

发布于 2024-12-12 09:33:47 字数 234 浏览 5 评论 0原文

据我了解,当我们在 ruby​​ 中添加两个数字时,会在当前对象上调用“+”方法,并将参数作为下一个对象。

>> 2 + 3
=> 5



>> 2.+(3)
=> 5

这两个例子有何相同之处?我们是否可以在没有点运算符的情况下调用对象的方法?第一个例子中是如何发生的?如果是这种情况,3 可能是在“+”方法上调用的方法方法吗? (这甚至没有意义)

As i understand when we add two numbers in ruby a '+' method is called on the current object with parameter as the the next object.

>> 2 + 3
=> 5



>> 2.+(3)
=> 5

How are these two examples same is it possible that we can call methods on objects without the dot operator ? How is it happening in the first example ? if that is the case the could 3 be an method method called on '+' method ? (It doesn't even make sense)

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

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

发布评论

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

评论(2

凝望流年 2024-12-19 09:33:47

Ruby 知道 + 是一个运算符,因为该语言的语法是这样规定的。还有一个一元 + 运算符(转换为 +@ 方法)并且语言的语法允许 Ruby 知道哪个是哪个。语言定义表明运算符是作为方法调用实现的,并指定每个运算符映射到哪个方法。

您所问的问题与询问 om a 如何使用 ao 调用 m 方法相同code> 作为参数。这就是 Ruby 的语法和语义的定义方式。

即使在理论数学中,运算符也是函数。 a + b 表示法实际上只是 +(a, b) 的方便表示法(其中 +:R2R 或从 R×RR 的函数,对于例子)。我认为您对符号的理解太多,并认为运算符是特殊的东西,但它们不是,它们只是计算机语言和数学中的函数调用。

简而言之,它之所以有效,是因为 Ruby 就是这样定义的。

据,直到...为止

3 可以是在“+”方法上调用的方法方法吗?

就而言,3 是 Fixnum 对象 2< 上的 + 方法的自变量参数 /代码>。

Ruby knows that + is an operator because the language's grammar says so. There's also a unary + operator (that is converted to the +@ method) and the language's grammar allows Ruby to know which is which. The language definition says that operators are implemented as method calls and specifies which method each operator maps to.

What you're asking is the same as asking how o.m a is a call to the m method on o with a as an argument. That's just how Ruby's syntax and semantics are defined.

Operators are functions even in theoretical mathematics. The a + b notation is really just a convenient notation for +(a, b) (where +:R2R or a function from R×R to R, for example). I think you're reading too much into the notation and thinking that operators are something special, they're not, they're just function calls in computer languages and mathematics alike.

In short, it works because that's how Ruby is defined to work.

As far as

could 3 be an method method called on '+' method ?

is concerned, 3 is an argument or parameter to the + method on the Fixnum object 2.

神也荒唐 2024-12-19 09:33:47

a + b 只是 a.+(b) 的糖语法。在 Ruby 中,几乎所有东西都是对象,甚至“运算符”实际上也是数字的方法。没有比糖语法更神奇的了。

The a + b is just sugar syntax for a.+(b). In ruby almost everything is an object, and even the 'operators' are really methods of a number. No more magic than sugar syntax.

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