I have the following code:
class Engine
attr开发者_如何学编程_accessor :isRunning
def initialize
@isRunning = false
@commands = ["left", "right", "brake", "accelerate", "quit"]
end
def start
self.isRunning = true;
while(self.isRunning)
command = gets.chomp!
if(@commands.include? command)
puts "OK."
else
puts "> #{command} Unknown Command."
end
if(command=="quit") then
self.stop
puts "Quitting!"
end
end
end
def stop
self.isRunning = false;
end
end
As you can see, it is pretty simple, however, I am trying to figure out how to invoke methods based on criteria. If I would implement a bunch of methods, like methodOne and methodTwo inside the Engine class like this:
@commands = ["left", "right", "brake", "accelerate", "quit", "methodOne", "methodTwo"]
def methodOne
end
def methodTwo
end
def parseCommand(command)
if(command=="methodOne") then
self.methodOne
end
if(command=="methodTwo") then
self.methodTwo
end
end
could I invoke these methods minimalistically? Right now, I would have to write a big pile of if-statements, and I would rather omit its future maintenance if it can be done more elegantly.
use self.send("methodname")
You can read more about it in the Docs
Your code could look like:
class Engine
# ...code ...
def parseCommands(commands)
commands.each{|c_command| self.send(c_command) }
end
# ...code ...
end
@commands = ["left", "right", "brake", "accelerate", "quit", "methodOne", "methodTwo"]
engineInstance.parseCommands(@commands)
精彩评论