在Ruby Programming Language , 第 6 章(第二段)他们说:
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.
然后在第6段的中间:
Both procs and lambdas are functions rather than methods invoked on an object.
我对这些说法有点困惑。 Ruby 是真正的纯 OO,因此没有与对象无关的函数(如果这是纯 OO 的有效定义),或者 procs/lambdas 是否与 Proc 对象相关联? Ruby 中的函数和方法有什么区别?
如果您能帮助我们解析和理解这一点,我们将不胜感激。
最佳答案
lambda
在 Ruby 中是类 Proc 的对象。 Proc
对象不属于任何对象。在不将它们绑定(bind)到对象的情况下调用它们。
方法是类 Method
或 UnboundMethod
的对象,具体取决于它们是绑定(bind)的还是未绑定(bind)的。看解释here .未绑定(bind)的方法在绑定(bind)到对象之前无法调用。
lambda{|x| x}.class # => Proc
lambda{|x| x}.call(123) # => 123
class Foo
def bar(baz)
baz
end
end
puts Foo.new.method(:bar).class # => Method
puts Foo.new.method(:bar).call(123) # => 123
puts Foo.instance_method(:bar).class # => UnboundMethod
puts Foo.instance_method(:bar).call(123) # => throws an exception
您可以绑定(bind)
一个UnboundMethod
到一个对象然后调用它。但是您根本无法将 Proc
bind
到一个对象。 Proc
对象可以捕获周围范围内的局部变量,成为闭包。
关于Ruby 函数与方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/928443/