hir*_*lau 0 ruby methods module
如何动态调用模块中的方法?
module Notification
def self.send_notification(title, message)
puts title + message
end
end
def test(string)
p string
end
if __FILE__ == $0
send("test", 'hello from test')
send("Notification.send_notification", 'hello', 'there') # Error: undefined method `Notification.send' for main:Object (NoMethodError)
end
Run Code Online (Sandbox Code Playgroud)
编辑:我的库中有多个模块,我确实需要能够将字符串转换为模块名称。假设我还有一个名为电子邮件的模块。也许 Eval 是唯一的方法?Edit2:重命名方法以免与内置发送方法冲突。
我看到唯一的方法,如果您希望通过名称定义为 a 来获取模块String,并且不使用#eval:
Object.const_get( 'Notification' ).send( 'send_notification', 'hello', 'there' )
# hellothere
Run Code Online (Sandbox Code Playgroud)
如果您想使用#eval,在许多情况下强烈不推荐:
eval( 'Notification' ).send( 'send_notification', 'hello', 'there' )
Run Code Online (Sandbox Code Playgroud)