2013-05-09 69 views
0

我在一個Rails應用程序的Order模型中,我希望爲Email類的實例調用一個方法。傳統test = method(arg)和test = send(method,arg)有什麼區別?

該第一種方法採用Email類的實例(在本例中稱爲email)。它工作得很好。

def recursive_search_mails(user, settings) 
    emails = user.emails.where(:datetime.gte => self.datetime) 

    emails.each do |email| 
    notification = email.test_if_notification(user, settings) 
    if notification == true 
     email.destroy 
     return 
    end 
    correspondance = email.test_if_correspondance(user, settings) 
    if correspondance == true 
     email.destroy 
     return 
    end 
    end 
end 

上面的代碼以更加簡潔的版本會是這樣:

def recursive_search_mails(user, settings) 
    emails = user.emails.where(:datetime.gte => self.datetime) 

    emails.each do |email| 
    %w(notification, correspondance).each do |type| 
     is_type = email.send("test_if_#{type}", user, settings) 
     if is_type == true 
     email.destroy 
     return 
     end 
    end 
    end 
end 

但是,它提出了這樣的錯誤:

2013-05-09T16:36:11Z 71266 TID-owr7xy0d0 WARN: undefined method `test_if_notification,' for #<Email:0x007fd3a3ecd9b0> 

怎麼能這樣呢?

回答

4

其他答案處理逗號,我會解決方法之間的差異。

當您事先不知道方法名稱(在「代碼編寫」時,缺少編譯時)時,您可以調用方法send。或者你知道,但執行「靜態」調用大大增加了代碼的複雜性(你的情況,重複代碼)。在這種情況下,需要動態調用(send)。

+0

我很尷尬,不知道我是否應該刪除這個問題或者誰來回答這個問題。當然,我不應該逗號。但是,謝謝@Sergio Tulentsev對於爲什麼send是有用的短暫的總結。 – JohnSmith1976 2013-05-09 17:12:50

+0

@ JohnSmith1976:不要擔心,它會發生在你新的時候:) – 2013-05-09 17:18:50

+0

是的。 Stackoverflow救援:-) – JohnSmith1976 2013-05-09 17:21:29

2

你不需要的逗號

變化

%w(notification, correspondance) 

%w(notification correspondance) 
3

%w文字前綴創建由空白分隔的標記的數組。

您有%w(notification, correspondence)其中包含字符串「通知」(注意逗號)和「通信」。

擺脫逗號,你應該很好。

+0

啊,錯過了那一個:) – 2013-05-09 17:01:23

相關問題