Ruby 1.8.6:如何将一个类中的常量别名为另一个类中的类方法?
有没有办法跨类创建别名?具体来说,从一个类中的常量到另一个类中的类方法?
类似的事情
Object.const_set('Foo', proc { Bar.meth })
除了在引用时自动评估 proc 之外, 。 (上面的 puts Foo
显示 proc #inspect
值;我需要执行 Foo.call
来实际调用 bar.meth
——这是我试图巧妙处理的额外步骤。)
换句话说,我想给一个常量起别名,这样当我说 puts Foo 它完全等同于
puts Bar.meth
。如果 Bar.meth
在不同时间返回不同的值,那么 Foo
也会相应地计算出不同的值 - 因为它们是相同的。
这可以做到吗?
谢谢!
Is there any way to create aliases across classes? Specifically, from a constant in one class to a class method in another?
Something like
Object.const_set('Foo', proc { Bar.meth })
except having the proc
auto-evaluated at reference-time. (puts Foo
for the above displays the proc #inspect
value; I need to execute Foo.call
to actually invoke bar.meth
-- and that's the extra step I'm trying to finesse around.)
Phrased another way, I would like to alias a constant such that when I say puts Foo
it is exactly equivalent to puts Bar.meth
. If Bar.meth
returns different values at different times, so would Foo
evaluate to the different values accordingly -- because they're the same.
Can this be done?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是你想要的吗?
This is what you want?
您可以在常量之间创建别名,
也可以将方法引用到其他类中。但是,由于常量的值是在评估赋值时详细说明的,因此您不能根据其他方法更改它。
您可以尝试通过将方法命名为常量来欺骗解释器
,但您只能调用
Bar.CONST
,而不能调用Bar::CONST
。此时,我有一个问题。你为什么要这么做?在我看来,这样的要求似乎凸显了一个设计问题。
You can create alias between constants
You can also reference a method into an other class. But because the value of the constant is elaborated when the assignment is evaluated, you cannot have it changing depending on an other method.
You can try to cheat the interpreter by naming the method like a constant
but you will only be able to call
Bar.CONST
, notBar::CONST
.At this point, I've got a question. Why should you do that? In my opinion, this kind of requirement seems to highlight a design issue.
上面的帖子真的很棒,但我也在控制台中进行了尝试,并通过不在 ruby 类“Object”中定义常量得到了略有不同的解决方案。
输出:
The post above is really great but i was also trying things out in console and got a slightly different solution by not defining a constant in the ruby class "Object".
Output: