Ruby `send` 与 `call` 方法 [英] Ruby `send` vs `call` method

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

问题描述

我正在阅读一篇关于 Ruby 1.9 的文章.call 方法和 Object 有很多用途.

I'm reading an article about Ruby 1.9. There are a lot of uses of the call method with Object.

但是使用最新版本的 Ruby,我得到了这个:

But with a recent version of Ruby, I get this:

BasicObject.methods.include? :send # => true
BasicObject.methods.include? :call # => false
Object.methods.include? :call # => false

def foo
  puts 'text'
end

Object.send :foo # => text
Object.call :foo # => NoMethodError: undefined method `call' for Object:Class

我认为在某些版本的 Ruby(可能是 1.9)中,方法被重命名了.但我不确定.请说清楚.

I think that in some version of Ruby (probably 1.9), method was renamed. But I'm not sure. Please make it clear.

推荐答案

首先,sendcall 是两种截然不同的方法.

To begin with, send and call are two very different methods.

在 ruby​​ 中,面向对象的概念源于 Smalltalk.基本上,当您调用一个方法时,您是在发送该对象一个消息.所以,当你想动态调用一个对象的方法时,你调用的方法是 send.该方法至少从 1.8.7 开始就存在于 ruby​​ 中.

In ruby, the concept of object orientation takes its roots from Smalltalk. Basically, when you call a method, you are sending that object a message. So, it makes sense that when you want to dynamically call a method on an object, the method you call is send. This method has existed in ruby since at least 1.8.7.

在 ruby​​ 中,我们也有块"的概念.块是附加到方法调用末尾的 do...end 东西.块可以传统地yielded;或者,完全可以从一个块中创建一个对象(a Proc),并传递它.为了执行该块,您可以调用 在块上调用.

In ruby, we also have a concept of "blocks". Blocks are the do...end things attached to the end of method calls. Blocks can be traditionally yielded to; or, it is entirely possible to create an object out of a block (a Proc), and pass that around. In order to execute the block, you can call call on the block.

call 从未在 Object 上定义过,而 send 是在所有东西上定义的.

call has never been defined on Object, whereas send is defined on everything.

(注意:出于某种原因,call 在 2.3.0 文档中似乎没有文档;但是,它仍然存在并且从 2.2.0 开始执行相同的操作,所以我改为链接那个.)

(note: for some reason, call doesn't seem to have documentation in the 2.3.0 documentation; however, it still exists and does the same thing from 2.2.0, so I linked that one instead.)

这篇关于Ruby `send` 与 `call` 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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