以下代码展示了如何从一个模块扩展一个类的实例方法 (include
) 和类方法 (extend
), 如何从一个模块扩展模块方法 (extend
).
但遇到一个奇怪的问题,当在模块中使用 class << self
后该模块不能被其他类或者模块引用 (无论是include
or extend
) 详见module D
, class S
, class Y
, 这是为什么?
module D
class << self
def say_hello_of_d
puts 'D say hello'
end
end
end
module E
def say_hello_of_e
puts 'E say hello'
end
end
module F
extend E
end
module G
include E
end
class H
extend E
end
class S
include E
end
class Y
include D
end
D.say_hello_of_d # D say hello
# E.say_hello_of_e # undefined method `say_hello_of_e' for E:Module
F.say_hello_of_e # E say hello
# G.say_hello_of_e # undefined method `say_hello_of_e' for G:Module
H.say_hello_of_e # E say hello
S.new.say_hello_of_e # E say hello
# Y.new.say_hello_of_d # undefined method `say_hello_of_d' for #<Y:0x000000013082b0>
Y.say_hello_of_d # undefined method `say_hello_of_d' for Y:Class
http://stackoverflow.com/questions/10039039/why-self-method-of-module-cannot-become-a-singleton-method-of-class https://www.ruby-forum.com/topic/4418176 http://blog.rubybestpractices.com/posts/gregory/041-issue-10.5-uses-for-modules.html http://www.techques.com/question/1-2353498/Is-extend-self-the-same-as-module_function? http://ruby-doc.com/docs/ProgrammingRuby/#Module.module_function