Search code examples
ruby-on-railsrubymethodsstring-interpolation

check if a interpolated method call is undefined


I have an interpolated method call, send("#{k}_track", k, v). I would like to run a check to see if the method that is being called is defined or not.

Something along the lines of next if send("#{k}_track", k, v) == undefined. The method that is being called is just a standalone method in a service.

I've tried using try or method_defined? but not luck. They just return the same undefined method error. So i'm not sure if this is even possible.


Solution

  • Use Object#respond_to?:

    send("#{k}_track", k, v) if respond_to?("#{k}_track")
    

    Or in the case with next:

    next unless respond_to?("#{k}_track")
    send("#{k}_track", k, v)