1

私は基本的にここで何が起こっているのか理解していません。以下のプレイは私のステートマシンです。しかし、うまくいきません。2 つの選択肢の反対、同じ選択肢を何度も (最初から) 返すか、「不明なコマンド」を返します。さまざまな時点で変数 @next_action の値を出力してテストしましたが、結果に一貫性がありません。case ステートメントの結果がinstructである場合もありますが、それはdisplayを出力します。その逆の場合もあれば、不明なコマンドの場合もあります。はい、コードをいじって、これらのさまざまな結果を生成します。しかし、それほど多くはありません。そして、期待どおりに動作したことはありません。

明らかに、私は自分が書いたものの論理を理解していません。私がやりたいことは、case ステートメントの結果をメソッド呼び出しとして渡し、すべてをループさせ続けることだけです。私はルビー初心者ですが、助けようとした一握りの人々は、私が理解していないように見える方法で物事を説明したり、私が何を説明したり正確に示したりするのに不十分な仕事をしたかのどちらかです.しようとしています。

どんな助けでも大歓迎です。

class Foo

  def initialize(start_action)
    @start = start_action
    @users = %w(Adam Sarah Kanye)
    @points = %w(100 200 300)
  end

  def play    
    puts @next_action
    while true
      case @next_action
      when beginning
        beginning
      when "instruct"
        instructions
      when "display"
        display_users
      else
        puts "Unknown command."
        play
      end
      puts "\n----------"
    end
  end

  def prompt
    puts "\n----------"
    print "> "
  end

  def beginning
    puts <<-INTROTEXT
      This is intro text.
    INTROTEXT
    prompt; @next_action = gets.chomp.to_s
  end

  def instructions
    puts <<-INSTRUCT
      These are instructions.
    INSTRUCT
    prompt; @next_action = gets.chomp.to_s
  end

  def display_users
    puts "\nYour users now include:"
    puts "\nName\tPoints"
    puts "----\t------"
    @users.each_with_index do |item, index|
      puts "%s\t%s" % [item, @points[index]]
    end
    prompt; @next_action = gets.chomp
  end
end

start = Foo.new(:beginning)
start.play
4

2 に答える 2

1

あなたは大丈夫です、ただ物事を少し乾かしてください. また、2 つの別個のループ構造が配置されているため、望ましくない動作が発生しています。メソッドには、それ自体が最後のステップとして:play呼び出す無限ループが含まれています。:play本当に必要なのはどちらかだけです。:prompt機能を一元化し、再帰なしでループを使用する (つまり:play、自分自身を呼び出さない) ように少し調整して、予想される動作を実現しました。

class Foo
  def initialize
    @next_action  = "beginning"
    @users        = %w(Adam Sarah Kanye)
    @points       = [100, 200, 300]
  end

  def play    
    while true
      act
      prompt
    end
  end

  def prompt
    puts "\n----------"
    print "> "
    @next_action = gets.chomp.to_s
  end    

  def act
    case @next_action
    when "beginning"
      beginning
    when "instruct"
      instructions
    when "display"
      display_users
    else
      puts "I don't know how to '#{@next_action}'."
    end
  end

  def beginning
    puts <<-INTROTEXT
      This is intro text.
    INTROTEXT
  end

  def instructions
    puts <<-INSTRUCT
      These are instructions.
    INSTRUCT
  end

  def display_users
    puts "\nYour users now include:"
    puts "\nName\tPoints"
    puts "----\t------"
    @users.each_with_index do |item, index|
      puts "%s\t%s" % [item, @points[index].to_s]
    end
  end
end

Foo.new.play
于 2013-06-06T16:19:24.070 に答える