gpt4 book ai didi

Ruby:根据条件调用方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:54:21 27 4
gpt4 key购买 nike

我有以下代码:

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

如您所见,它非常简单,但是,我正在尝试弄清楚如何根据条件调用方法。如果我像这样在 Engine 类中实现一堆方法,比如 methodOne 和 methodTwo:

@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

我可以简单地调用这些方法吗?现在,我不得不写一大堆 if 语句,如果可以更优雅地完成,我宁愿省略它的 future 维护。

最佳答案

使用 self.send("methodname")

您可以在 Docs 中阅读更多相关信息

您的代码可能如下所示:

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)

关于Ruby:根据条件调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5205333/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com