Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.