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
How can I convert string input to method call?
Assume I have a object called MyObject
# do something
# do something else
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?
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.
action = action.to_sym
Also depending on what you're looking to do with this sort of method you may want to look into the inner workings of