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 trialJiaming Zhang
10,170 PointsHow 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
Geoff Parsons
11,679 PointsYou 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
.
Geoff Parsons
11,679 PointsGeoff Parsons
11,679 PointsActually the cast to a symbol isn't even necessary -
send
andrespond_to?
both accept strings.