我有一个类定义了一个常量。然后我定义了一个类方法来访问那个类的常量。这工作正常。一个例子:(在Ruby中)允许混合类方法访问类常量
#! /usr/bin/env ruby
class NonInstantiableClass
Const = "hello, world!"
class << self
def shout_my_constant
puts Const.upcase
end
end
end
NonInstantiableClass.shout_my_constant
在试图移出此类方法到外部模块,像这样我的问题出现了:
#! /usr/bin/env ruby
module CommonMethods
def shout_my_constant
puts Const.upcase
end
end
class NonInstantiableClass
Const = "hello, world!"
class << self
include CommonMethods
end
end
NonInstantiableClass.shout_my_constant
红宝石解释方法从模块请求的常数,而不是该类:
line 5:in `shout_my_constant': uninitialized constant CommonMethods::Const (NameError)
那么,你有什么魔术技巧让同伴们不得不让方法访问类常量?非常感谢。
那么,这清除了事情。我还没有体验::语法:)。 – jameshfisher 2009-12-13 21:14:31
现在不要停止阅读。请阅读下面的约翰内斯回应。 – Sebastian 2014-04-10 07:22:12