Search code examples
rubyuser-inputtic-tac-toe

user input doesn't get processed


I am a newbie and really stuck with this problem. I need the array element that matches the user input to be replaced with "X". What am I doing wrong? Can you please help!? Thanks!

class Round 

  def start 
    display_board
    pick
    refresh_board
  end

  #displays the board in the begining of the game
  def display_board
    @board = [[1,2,3],[4,5,6],[7,8,9]]
    @board.each do |i|
      puts i.join("|")
    end
  end

  def refresh_board
    @changed_board = []
    @board.each do |i|
      if i.include?(@input)
        r = i.index(@input)
        i[r] = "X"
        @changed_board << i
      else
        @changed_board << i
      end
    end

    @changed_board.each do |i|
      puts i.join("|")
    end
  end

 #player selects a number
  def pick
    puts "player1, select a number:"
    @input = gets.chomp
  end
end

round1 = Round.new 
round1.start

Solution

  • The method i.include?(@input) never returns true because the array i is made of Integer, and @input is a String.

    That's what's happening:

    [1,2,3].include?("1") #=> false
    

    To make it work, you can convert @input to Integer when setting it.

    Another thing: as well pointed by @JörgWMittag, you don't need String#chomp, as to_i ignores whitespaces as well.

    Just replace this line:

    @input = gets.chomp
    

    with:

    @input = gets.to_i
    

    And it will work!