无法使用包含?在方法中使用实例变量

时间:2019-12-10 18:48:44

标签: ruby

我试图使用'gets'来获取输入,然后检查实例变量是否在方法内部包括了输入,但是我无法使其正常工作。这是代码:

class Game
    attr_accessor :available_moves

    def initialize
        @available_moves = ["0","1","2","3","4","5","6","7","8"]
    end

  def play_game
    puts ("Welcome")
    while true
        puts "Player 1, choose a square"
        player1_choice = gets
        # v this is what I can't get to work v
        if @available_moves.include?(player1_choice) 
            puts "yes"
            break
        else
            puts "no"
        end
    end
end
end

game1 = Game.new
game1.play_game

无论我尝试什么,都满足“ else”条件,并且打印“ no”。

1 个答案:

答案 0 :(得分:1)

当用户使用gets输入文本时,他们按Enter键,这将发送换行符。您需要使用gets.chomp删除换行符:

class Game
  attr_accessor :available_moves

  def initialize
    @available_moves = ["0","1","2","3","4","5","6","7","8"]
  end

  def play_game
    puts ("Welcome")
    while true
      puts "Player 1, choose a square"
      # Note the .chomp here to remove the newline that the user inputs
      player1_choice = gets.chomp
      # v this is what I can't get to work v
      if @available_moves.include?(player1_choice) 
        puts "yes"
        break
      else
        puts "no"
      end
    end
  end
end

game1 = Game.new
game1.play_game

现在,您得到了:

game1.play_game
Welcome
Player 1, choose a square
1
yes
=> nil

有关更深入的说明,请参见How does gets and gets.chomp in ruby work?