Ruby在send和instance

编程入门 行业动态 更新时间:2024-10-07 16:25:23
本文介绍了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

本文发布于:2023-11-25 06:22:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Ruby   send   instance

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!