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:'personal_list', {date: [1.month], config: true}).print_users  
class UserService  
  def initialize(string, opts = {})
    @string = string
    @date = opts[:date]
    @config = opts[:config]

  def print_users

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


  def personal_list

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. Director of Engineering 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!