1
23
本工程(在IRB中测试):
注意:此项仅作更改
这是因为你要打开str's
singleton class
在那里定义一个方法。因为这个,以及打电话给
Module#define_method
,有一些人称之为“平面范围”,如果使用
您可以在这里查看其他一些“元编程拼写: media.pragprog.com/titles/ppmetr/spells.pdf
因为鲁比有几个有趣的把戏。在Ruby对象模型中,方法调用不仅会导致Receiver搜索它的类(和
它的
祖先),但它也是单子类(或者如Matz所说,它是本征类)。这个singleton类允许您为单个对象[重新]定义一个方法。这些方法称为“单例方法”。在上面的示例中,我们只是这样做-定义一个单例方法名
唯一的区别是我们在调用
为什么不能简单一点? 好消息是,你正在用Ruby编程,所以你可以随意发疯了:
如果你好奇的话… 你知道课堂方法吗?或者,在某些语言中,我们称它们为静态方法?嗯,那些不是 真的? 存在于红宝石中。在Ruby中,类方法实际上只是类对象的singleton类中定义的方法。 如果这一切听起来很疯狂,看看我上面提供的链接。只有知道如何进行元编程,才能充分利用Ruby的强大功能——在这种情况下,您真的需要了解单例类/方法,更一般地说,还需要了解Ruby对象模型。 高温高压 -查尔斯 |
2
9
Feature #1082 在Ruby1.9.2中实现使这项任务变得简单 Object#define_singleton_method :
所涉及的概念与我的
previous answer
它提供了一个更深入的描述,说明了Ruby的对象模型中如何工作,以及
您可能会发现对类似任务有用的其他方法: |
3
0
这似乎奏效了。
问题是代码在
和
|
Stilian · 存储库设置中没有Github页面部分 2 年前 |
Kellen · 查看$卷展栏功能列表 2 年前 |
Akshit Thakur Ak · 我怎样才能把铁轨停下来? 2 年前 |
johncssjs · 将数组转换为每个元素的嵌套哈希 2 年前 |
solidsnake99 · Rails db:如何绕过验证 2 年前 |