Ruby在send和instance_eval之间的区别? [英] Ruby difference between send and instance_eval?

查看:98
本文介绍了Ruby在send和instance_eval之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道send接受带有参数的字符串或符号,而instance_eval接受带有字符串或块的参数,并且给定接收者,它们的区别可能显而易见.

I know send takes string or symbol with arguments while instance_eval takes string or block, and their difference could be apparent given receivers.

我的问题是,下面的示例的"内幕"有什么区别?

My question is what the 'under the hood' difference is for the example below?

1234.send 'to_s'               # '1234'
1234.instance_eval 'to_s'      # '1234'

推荐答案

来自

发送(符号[,args ...])→obj
发送(字符串[,args ...])→obj

send(symbol [, args...]) → obj
send(string [, args...]) → obj

调用由 symbol 标识的方法,并将指定的任何参数传递给该方法. [...]当方法由字符串标识时,该字符串将转换为符号.

Invokes the method identified by symbol, passing it any arguments specified. [...] When the method is identified by a string, the string is converted to a symbol.

,对于 instance_eval :

instance_eval(string [,filename [,lineno]])→obj
instance_eval {| |阻止}→obj

instance_eval(string [, filename [, lineno]] ) → obj
instance_eval {| | block } → obj

在接收方( obj )的上下文中评估包含Ruby源代码或给定块的字符串.为了设置上下文,在代码执行时将变量self设置为 obj ,使代码可以访问 obj 的实例变量.

Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables.

因此send执行一个方法,而instance_eval执行任意代码块(作为字符串或块),并将self设置为您要调用instance_eval的对象.

So send executes a method whereas instance_eval executes an arbitrary block of code (as a string or block) with self set to the object that you're calling instance_eval on.

在您的情况下,差别不大,因为您要传递给instance_eval的字符串只是一个方法.主要区别在于,任何阅读您的代码的人(包括六个月内的您)都会想知道您为什么使用instance_eval调用单个方法.

In your case, there isn't much difference as the string you're handing to instance_eval is just a single method. The main difference is that anyone reading your code (including you in six months) will be wondering why you're using instance_eval to call a single method.

您可能还对 Object#public_send 感兴趣.和 BasicObject#__send__

You might also be interested in Object#public_send and BasicObject#__send__

这篇关于Ruby在send和instance_eval之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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