Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

How can I convert string input to method call?

Assume I have a object called MyObject

class MyObject
  def foo
    # do something
  end

  def bar
    # do something else
  end
end

I want to create a function that take string as input. If the string equal to "foo", call the foo method, if the string equal to "bar", call the "foo" method, if the string equal neither, do nothing.

In Ruby, how can I achieve what I just describe?

1 Answer

You can always use the send method. It accepts a symbol, so simply cast the argument to a symbol before calling it. This in combination with respond_to? may be what you're looking for.

  def do_something(action)
    action = action.to_sym
    if respond_to?(action)
      send(action)
    end
  end

Also depending on what you're looking to do with this sort of method you may want to look into the inner workings of method_missing.

Actually the cast to a symbol isn't even necessary - send and respond_to? both accept strings.