Ruby 函数与方法
在 Ruby 编程语言第 6 章(第二段)中,他们指出:
许多语言都区分 没有关联的函数 调用的对象和方法 在接收者对象上。 因为鲁比是 纯粹的面向对象语言,所有 方法是真正的方法并且是 与至少一个对象关联。
然后在第6段中间:
procs 和 lambda 都是函数 而不是调用方法 对象。
我对这些说法有点困惑。 Ruby 是真正的纯 OO,因此不具有与对象无关的函数(如果这是纯 OO 的有效定义),或者 procs/lambda 与 Proc 对象关联吗? Ruby 中的函数和方法有什么区别?
任何有助于解析和理解这一点的帮助将不胜感激。
In the Ruby Programming Language, Chapter 6 (second paragraph) they state:
Many languages distinguish between
functions, which have no associated
object, and methods, which are invoked
on a receiver object. Because Ruby is
a purely object oriented language, all
methods are true methods and are
associated with at least one object.
And then in the middle of the 6th paragraph:
Both procs and lambdas are functions
rather than methods invoked on an
object.
I am a bit confused about these statements. Is Ruby truly pure OO, and therefore doesn't have functions that aren't associated with objects (if that is a valid definition of pure OO), or are procs/lambdas associated with the Proc object? What is the difference between functions and methods in Ruby?
Any help in parsing and understanding this would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ruby 中的 lambda 是 Proc 类的对象。
Proc
对象不属于任何对象。 调用它们时无需将它们绑定到对象。方法是
Method
类或UnboundMethod
类的对象,具体取决于它们是绑定还是未绑定。 请参阅此处的说明。 未绑定的方法在绑定到对象之前无法调用。您可以将
UnboundMethod
绑定
到一个对象,然后调用它。 但是您根本无法将Proc
绑定到对象。 然而,Proc 对象可以捕获周围范围内的局部变量,成为闭包。lambda
s in Ruby are objects of class Proc.Proc
objects don't belong to any object. They are called without binding them to an object.Methods are objects of either class
Method
orUnboundMethod
, depending on whether they're bound or unbound. See the explanation here. Unbound methods can't be called until they're bound to an object.You can
bind
anUnboundMethod
to an object and then call it. But you can'tbind
aProc
to an object at all.Proc
objects can however capture local variables in the surrounding scope, becoming closures.Procs 和 lambda 本身都是对象,具有实际调用与 proc(或 lambda)关联的块的
call
方法。 然而,Ruby 提供了一些语法糖来调用它们,而无需显式调用call
。Procs and lambdas are both objects unto themselves, with a
call
method that actually invokes the block associated with the proc (or lambda). However, Ruby provides some syntactic sugar to invoke them without the explicit call tocall
.我认为区别在于方法和 一阶函数 即。 可以作为值传递的函数。
I think the distinction is between methods and first order function ie. functions that can be passed around as values.