如果(出于何种原因)我extend Stuff
class Dog
如何通过Dog类访问CONST1
?我知道我可以通过说Stuff::CONST1
得到CONST1,但是如何通过狗得到它。我也知道,如果我include Stuff
中的class Dog
,此代码就可以使用。
module Stuff
CONST1 = "Roll Over"
end
class Dog
extend Stuff
end
Dog::CONST1 #NameError: uninitialized constant Dog::CONST1
答案 0 :(得分:3)
您可能会考虑include
,而不是extend
。
extend
添加了实例方法:
从作为参数给出的每个模块中添加 obj 实例方法。
但是include
:
以相反的顺序在每个参数上调用
Module.append_features
。
Ruby的默认实现是将此模块的常量,方法和模块变量添加到 mod ,如果此模块尚未添加到 mod 或其祖先之一。
所以,如果你这样做:
module M
PANCAKES = 11
end
class C
include M
end
然后,您可以从PANCAKES
获取C
:
puts C::PANCAKES
# gives you 11
答案 1 :(得分:2)
答案 2 :(得分:0)
使用:
module Stuff
CONST1 = "Roll Over"
end
class Dog
include Stuff
end
Dog::CONST1 # works
请参阅What is the difference between include and extend in Ruby?