ruby - What is the difference between the traditional test = method(arg) and test = send(method, arg)? -


i in order model of rails application, wish invoke method instance of email class.

this first method takes instance of email class (in example called email). works fine.

def recursive_search_mails(user, settings)   emails = user.emails.where(:datetime.gte => self.datetime)    emails.each |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 

a more concise version of above code one:

def recursive_search_mails(user, settings)   emails = user.emails.where(:datetime.gte => self.datetime)    emails.each |email|     %w(notification, correspondance).each |type|       is_type = email.send("test_if_#{type}", user, settings)       if is_type == true         email.destroy         return       end     end   end end 

however, raises error:

2013-05-09t16:36:11z 71266 tid-owr7xy0d0 warn: undefined method `test_if_notification,' #<email:0x007fd3a3ecd9b0> 

how can be?

other answers deal comma, i'll address difference between approaches.

you invoke methods send when don't know method name in advance (at "code-write" time, lack of compile-time). or know, performing "static" calls increases complexity of code (your case, duplicated code). in such cases, dynamic invocation (send) called for.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -