我在一個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>
怎麼能這樣呢?
我很尷尬,不知道我是否應該刪除這個問題或者誰來回答這個問題。當然,我不應該逗號。但是,謝謝@Sergio Tulentsev對於爲什麼send是有用的短暫的總結。 – JohnSmith1976 2013-05-09 17:12:50
@ JohnSmith1976:不要擔心,它會發生在你新的時候:) – 2013-05-09 17:18:50
是的。 Stackoverflow救援:-) – JohnSmith1976 2013-05-09 17:21:29