具有来自包含器类的静态方法调用的 Ruby 模块
我需要在模块中定义使用包含该模块的类中的方法的常量:
module B
def self.included(base)
class << base
CONST = self.find
end
end
end
class A
def self.find
"AAA"
end
include B
end
puts A::CONST
但是编译器在第四行给出错误。
还有其他方法来定义常数吗?
I need to define the constant in the module that use the method from the class that includes this module:
module B
def self.included(base)
class << base
CONST = self.find
end
end
end
class A
def self.find
"AAA"
end
include B
end
puts A::CONST
But the compiler gives the error on the 4th line.
Is there any other way to define the constant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Ruby 中实现此目的更惯用的方法是:
您所做的(class << base)实际上将您置于 A 的
metaclass
的上下文中,而不是 A 本身。find
方法位于 A 本身,而不是其元类。 要记住的是,类本身就是对象,因此有自己的元类。尝试使其更清楚:
不确定这是否有帮助,但如果您不理解它,您仍然可以使用上面的 class_eval 习惯用法。
The more idiomatic way to achieve this in Ruby is:
What you were doing (class << base) actually puts you into the context of A's
metaclass
, not A itself. Thefind
method is on A itself, not its metaclass. The thing to keep in mind is that classes are themselves objects, and so have their own metaclasses.To try to make it clearer:
Not sure if that helps, but if you don't understand it, you can still use the class_eval idiom above.
根据你的具体情况。
尽管它有效,但有点混乱。 您确定不能采用不同的方式来实现您的目标吗?
In your specific case.
Despite it works, it's a little bit messy. Are you sure you can't follow a different way to achieve your goal?
然后编译器错误已修复,请尝试。
then the compiler error is fixed, pls try.