Ruby函数与方法 [英] Ruby functions vs methods

查看:171
本文介绍了Ruby函数与方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby编程语言第6章(第二段)中,他们声明:


许多语言将
函数(它们没有关联的
对象)和方法(它们调用
在接收器对象上。由于Ruby是纯粹面向对象的
语言,所有
方法都是真正的方法,并且
至少与一个对象相关联。


然后在第六段中:


procs和lambdas都是函数
而不是而不是在
对象上调用的方法。


我对这些语句有些困惑。 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:

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.

解决方案

lambdas 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函数与方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆