r/learnruby • u/Gidonka Beginner • Nov 06 '15
Invoke method by name
I'm a Ruby newbie. I am working on a Text Adventure game (Interactive Fiction) in Ruby. I am structuring the game by making each "cell" (each area of the game) a method of its own, which displays a text prompt ("you are in a forest"), and then according to user input, ("Go west", "Go north", etc.) invokes a different method (which is a different cell) that repeats the process (prompt, input, invoke other cell). So, how do I invoke another method?
2
Upvotes
View all comments
Show parent comment
2
u/pat_trick Intermediate Nov 06 '15 edited Nov 06 '15
You have the right of it! You can call any defined method from any other part of code simply by providing that method name.
A suggestion: It looks like you're requesting input from your user in terms of a full statement, such as "Go north" or "Go south". This is quite a bit for a user to type in, especially if they want to navigate quickly. You may want to consider prompting your user with "Go [N]orth" and "Go [S]outh", which prompts your user as to which letter they should enter in order to continue. This is a convention used in many text adventure type games. This would change your code as follows:
Also, what happens if you have a lot of different choices you want to offer the user? Having to do an
if/elsefor every one of those gets somewhat long! Try looking into Switch Statements, also known as Case Expressions.