新手问题:
我知道include和extend是如何工作的,我想知道的是,是否有一种方法可以从一个模块中同时获得类和示例方法?
这是我如何用两个模块来做的:
module InstanceMethods
def mod1
"mod1"
end
end
module ClassMethods
def mod2
"mod2"
end
end
class Testing
include InstanceMethods
extend ClassMethods
end
t = Testing.new
puts t.mod1
puts Testing::mod2
字符串
感谢您抽出时间...
3条答案
按热度按时间3yhwsihp1#
有一个常见的习惯用法。它使用
included
对象模型钩子。每当一个模块被包含到一个模块/类中时,这个钩子就会被调用。字符串
我个人也喜欢将示例方法分组到一个嵌套模块中,但据我所知,这是不太被接受的做法。
型
jq6vz3qz2#
字符串
pkbketx93#
是的。就像你想象的那样简单,因为Ruby的天才:
字符串
或者,你可以这样做:
型