0

只要用户输入方法名称,下面的代码就可以完全正常工作。我想避免要求用户在各种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

任何建议或帮助表示赞赏。

4

1 回答 1

0

在第一次通过循环时,next_action符号:beginning和符号没有include?方法。

此外,我认为您误解了 case 语句的工作原理-即使删除第一个错误,您的代码也会抱怨您将 0 参数传递给include?(而不是 1)

我认为你的意思是

case next_action
when /instruct/
  ..
when /users
   ..
else
  ..
end

这将依次测试针对每个常规压制的下一步行动

于 2013-06-04T20:38:55.697 回答