1

I'm trying to replace an array with a new array, replacing values as I go along.

Here's the code:

minesarray = [['*','.','.','.'],['.','.','*','.'],['.','.','.','.']]

def pp_board(board)
    puts Array.new(board[0].size*2+1, '-').join('')
    board.each do |row|
        puts "|" + row.join("|") + "|"
        puts Array.new(row.size*2+1, '-').join('')
    end
end

pp_board(minesarray)

count = 0

minesarray.map{ |row|
    row.each { |col|
        if minesarray[row][col] = '*'
            minesarray[row][col]="a"
        elif minesarray[row][col] = '.'
            minesarray[row][col] = 0
        end
    }
}

I receive the following error:

mines2.rb:17:in '[]': can't convert Array into Integer (TypeError)
   from mines2.rb:17:in 'block (2 levels) in (main)'
   from mines2.rb:16:in 'each'
   from mines2.rb:16:in 'block in (main)'
   from mines2.rb:15:in 'map'
   from mines2.rb:15:in '(main)'
1
  • Start with elif => elsif, and fix if minesarray[row][col] = '*' Commented Apr 8, 2015 at 3:42

2 Answers 2

2

The row and col is not the index of the array, but the element itself.

You could do like below:

minesarray = [['*','.','.','.'],['.','.','*','.'],['.','.','.','.']]

def pp_board(board)
    puts Array.new(board[0].size*2+1, '-').join('')
    board.each do |row|
        puts "|" + row.join("|") + "|"
        puts Array.new(row.size*2+1, '-').join('')
    end
end

pp_board(minesarray)

minesarray = minesarray.map { |row|
  row.map { |v|
    if v == '*'
      'a'
    elsif v == '.'
      '0'
    end
  }
}

pp_board(minesarray)
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that row and col are not indexes, they are the actual elements of the array.

You also have a couple of other issues. "elif" should be elsif and you're using assignment (=) in your conditionals where you should be using an equality check (==).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.