How to convert a string to a method name in Ruby

What if I want to send a string as a param to a service and then with that string param call a method with the same name?

For example:

UserService.new('personal_list', {date: [1.month], config: true}).print_users  
class UserService  
  def initialize(string, opts = {})
    @string = string
    @date = opts[:date]
    @config = opts[:config]
  end

  def print_users
    cardinal 
  end

  def cardinal
    send(@string) if self.class.private_method_defined?(@string)
  end

  private

  def personal_list
    User.all
  end
end  

So the one that does the trick is send

Clear explanation send vs call

That's all folks!

You should follow me on twitter @zazvick

Disclaimer: This example was merely representative and has the purpose of illustrating how to convert a string to a method.

Update: This post it was updated to use self.class.privatemethoddefined? instead of declaring an array with and check if the string is included in that array. 2017/10/11

Victor Velazquez

Coder, Musician, Startups, Passionate Dancer & Life Lover. Software Engineer at MagmaLabs, Co-founder of Web Dev Talks, Co-founder of Voltaire, Co-founder of Paqkit, Ex-co-founder of Zaznova.

Subscribe to The zazvick's blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!