当我们在 ruby 中使用运算符时会发生什么
据我了解,当我们在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ruby 知道
+
是一个运算符,因为该语言的语法是这样规定的。还有一个一元+
运算符(转换为+@
方法)并且语言的语法允许 Ruby 知道哪个是哪个。语言定义表明运算符是作为方法调用实现的,并指定每个运算符映射到哪个方法。您所问的问题与询问
om a
如何使用a
o 调用m
方法相同code> 作为参数。这就是 Ruby 的语法和语义的定义方式。即使在理论数学中,运算符也是函数。
a + b
表示法实际上只是+(a, b)
的方便表示法(其中+
:R2→R 或从 R×R 到 R 的函数,对于例子)。我认为您对符号的理解太多,并认为运算符是特殊的东西,但它们不是,它们只是计算机语言和数学中的函数调用。简而言之,它之所以有效,是因为 Ruby 就是这样定义的。
据,直到...为止
就而言,
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 them
method ono
witha
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+
:R2→R 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
is concerned,
3
is an argument or parameter to the+
method on the Fixnum object2
.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.