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 ステートメントがどのように機能するかを誤解していると思います。最初のエラーを削除しても、コードはinclude?(1 ではなく) 0 の引数を渡していると不平を言います。

代わりに次のような意味だと思います

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

通常の抑圧ごとに次のアクションを順番にテストします

于 2013-06-04T20:38:55.697 に答える