问题描述
在第6章(第二段)中,他们声明:
然后在第六段中:
我对这些语句有些困惑。 Ruby是否是真正的纯OO,因此没有与对象关联的函数(如果这是纯OO的有效定义),或者是与Proc对象关联的procs / lambdas?在Ruby中的函数和方法有什么区别?
任何帮助解析和理解这个都是值得赞赏的。 Ruby中的对象是类Proc的对象。 Proc
对象不属于任何对象。
$ b 方法是类方法
或<$ c $的对象c> UnboundMethod ,具体取决于它们是绑定还是非绑定。请参阅的解释。未绑定的方法只有绑定到对象后才能被调用。
lambda {| x | x} .class#=> Proc
lambda {| x | x} .call(123)#=> 123
class Foo
def bar(baz)
baz
end
end
把Foo.new.method :bar).class#=>方法
放置Foo.new.method(:bar).call(123)#=> 123
puts Foo.instance_method(:bar).class#=> UnboundMethod
puts Foo.instance_method(:bar).call(123)#=>引发异常
您可以绑定
an UnboundMethod
到一个对象,然后调用它。但是你完全可以将 bind
a Proc
绑定到一个对象。然而, Proc
对象可以捕获周围范围内的局部变量,成为闭包。
In the Ruby Programming Language, Chapter 6 (second paragraph) they state:
And then in the middle of the 6th paragraph:
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.
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
or UnboundMethod
, 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.
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
You can bind
an UnboundMethod
to an object and then call it. But you can't bind
a Proc
to an object at all. Proc
objects can however capture local variables in the surrounding scope, becoming closures.
这篇关于Ruby函数与方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!