I\'m playing with writing a MUD/text adventure (please don\'t laugh) in Ruby. Can anyone give me any pointers towards an elegant, oop-based solution to parsing input text? <
For command interpreters, I'm rather fond of this simple, not all that elegant pattern. Patterns in dynamic languages tend to involve fewer boxes and lines than GOF patterns.
class Thing
# Handle a command by calling the method "cmd_" + command.
# Raise BadCommand exception if there is no method for that command.
def handle_command(command, args)
method_name = "cmd_#{command}"
raise BadCommand, command unless respond_to?(method_name)
send(method_name, args)
end
def cmd_quit(args)
# the code for command "quit"
end
def cmd_list(args)
# the code for command "list"
end
...
end
In this way, adding a new command is just adding a new method. No tables or case statements need to be adjusted.