只要用户输入方法名称,下面的代码就可以完全正常工作。我想避免要求用户在各种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
任何建议或帮助表示赞赏。