只要用户输入方法名称,下面的代码就可以正常运行。我想避免要求用户在各种gets.chomp提示符下输入方法的名称。
我认为使用case语句将用户输入转换为方法调用是可行的,但我一直得到一个.include? NoMethodDefined错误。
class Foo
def initialize(start_action)
@start = start_action
end
def play
next_action = @start
while true
case next_action.include?
when beginning
next_action = beginning
when "instruct"
next_action = instructions # returns instructions as
# the method that's called below
when "users"
next_action = users # returns users as the
# method that's called below
else
puts "Unknown command."
next_action = # some placeholder method call that gets the user
# back to being able to make another choice
end
puts "\n----------"
next_action = method(next_action).call
end
def beginning
puts "This is the beginning."
next_action = gets.chomp
end
def instructions
puts "These are the instructions"
# code to display instructions omitted
next_action = gets.chomp
end
def users
puts "Here are your users"
# code to display users omitted
next_action = gets.chomp
end
end
start = Foo.new(:beginning)
start.play
感谢任何建议或帮助。
答案 0 :(得分:0)
在第一次通过循环时,next_action
是符号:beginning
,符号没有include?
方法。
此外,我认为您误解了案例陈述的工作原理 - 即使删除了第一个错误,您的代码也会抱怨您将0个参数传递给include?
(而不是1)
我认为你的意思是
case next_action
when /instruct/
..
when /users
..
else
..
end
将依次针对每个常规压制测试下一步行动