2014-01-31 66 views
-1

如何動態調用模塊中的方法?動態調用模塊中的方法?

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 

編輯: 我在圖書館一個以上的模塊,我真的需要能夠將字符串轉換爲模塊名。假設我也有一個稱爲電子郵件的模塊。也許Eval是唯一的方法? Edit2: 爲了不與內置的send-method衝突而重命名的方法。

回答

3

我看到的唯一途徑,如果你希望得到的名字的模塊定義爲String,而不要使用#eval

Object.const_get('Notification').send('send_notification', 'hello', 'there') 
# hellothere 

如果您想使用#eval是強烈不在很多情況下推薦:

eval('Notification').send('send_notification', 'hello', 'there') 
+0

正是我在找的東西。 – hirolau