0

I am trying to use 'gets' to get input and then check to see if the instance variable includes the input inside of a method but I can't get it work. Here is the code:

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

No matter what I try, the 'else' condition is met and "no" is printed.

Robert
  • 79
  • 1
  • 2
  • 8

1 Answers1

1

When the user inputs text with gets they press Enter, which sends a newline. You need to remove the newline with 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

Now you get:

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

See How does gets and gets.chomp in ruby work? for a more in-depth explanation.

anothermh
  • 9,815
  • 3
  • 33
  • 52