我需要在模块中定义使用包含该模块的类中的方法的常量:
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
但是编译器在第4行给出了错误。
还有其他方法来定义常数吗?
在 Ruby 中实现此目的更惯用的方法是:
module B
def self.included(klass)
klass.class_eval <<-ruby_eval
CONST = find
ruby_eval
# note that the block form of class_eval won't work
# because you can't assign a constant inside a method
end
end
class A
def self.find
"AAA"
end
include B
end
puts A::CONST
你正在做的事情 (class metaclass,而不是 A 本身。这find
方法位于 A 本身,而不是其元类。要记住的是,类本身就是对象,因此有自己的元类。
试着让它更清楚:
class Human
def parent
# this method is on the Human class and available
# to all instances of Human.
end
class << self
def build
# this method is on the Human metaclass, and
# available to its instance, Human itself.
end
# the "self" here is Human's metaclass, so build
# cannot be called.
end
def self.build
# exactly the same as the above
end
build # the "self" here is Human itself, so build can
# be called
end
不确定这是否有帮助,但如果您不理解它,您仍然可以使用上面的 class_eval 习惯用法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)