【发布时间】:2017-02-04 05:36:53
【问题描述】:
例如我有以下自定义类和模块:
module SimpleModule
def hello_world
puts 'i am a SimpleModule method'
end
def self.class_hello_world
puts 'i am a SimpleModule class method'
end
end
class SimpleClass
def hello_world
puts 'i am SimpleClass method'
end
def self.class_hello_world
puts 'i am a SimpleClass class method'
end
end
我尝试使用方法send在类和模块中调用这些方法
SimpleClass.send(class_hello_world) # work
SimpleClass.new.send(hello_world) # work
SimpleModule.send(class_hello_world) # work
SimpleModule.new.send(hello_world) # not work
SimpleModule.send(hello_world) # not work
换句话说,我不知道如何从SimpleModule 调用hello_world。如果该方法之前用 self 定义过,这是可能的。
我需要这样做是因为我想实现一个“自定义包含”:它包含从模块到另一个类的所有方法。
请告诉我该怎么做。
【问题讨论】:
-
SimpleModule.new.send(hello_world)不起作用,因为您不能拥有模块的实例。 -
@EddeAlmeida 谢谢。所以Ruby通过它的语言实现关键字“include”或者我可以通过使用元编程来做类似的事情?如果元编程可能,应该有一种从模块调用方法的方法。
标签: ruby metaprogramming