Ruby在send和instance_eval之间的区别? [英] Ruby difference between send and 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 send(symbol [, 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(string [,filename [,lineno]])→obj instance_eval(string [, filename [, lineno]] ) → obj 在接收方( obj )的上下文中评估包含Ruby源代码或给定块的字符串.为了设置上下文,在代码执行时将变量 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 因此 So 在您的情况下,差别不大,因为您要传递给 In your case, there isn't much difference as the string you're handing to 您可能还对 You might also be interested in 这篇关于Ruby在send和instance_eval之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
发送(字符串[,args ...])→obj
send(string [, args...]) → objinstance_eval
:
instance_eval {| |阻止}→obj
instance_eval {| | block } → objself
设置为 obj ,使代码可以访问 obj 的实例变量.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
的对象.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
调用单个方法.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__
Object#public_send
and BasicObject#__send__