Daniel Bonnell
Daniel Bonnell

Reputation: 4997

Iterate through an array using each_with_index without a separate index variable

I am trying to figure out how I can refactor my code below so that I can iterate through the array without using the "index1" and "index2" variables to keep track of my progress.

  board.each do |cell|
    diag1 << cell[index1]
    diag2 << cell[index2]
    index1 += 1
    index2 -= 1
  end

I tried using .each_with_index (see below), but I'm not sure how to increment my values for "i".

  board.each_with_index do |cell, i|
    diag1 << cell[i += 1]
    diag2 << cell[i -= 1]
  end

The array "board" is an n*n array of a tic-tac-to game that is at least 3x3 in size or larger and the block of code is supposed to check to see if there is a diagonal match. Thanks in advance!

Edit: Figured it out. Here is the working code snippet:

  board.each_with_index do |cell, i|
    diag1 << cell[i]
    diag2 << cell[-(i +1)]
  end

Upvotes: 1

Views: 493

Answers (1)

BroiSatse
BroiSatse

Reputation: 44685

You can do:

diag1, diag2 = board.map.with_index {|row, i| [row[i],row[-i-1]]}.transpose

The main trick I'm using here is array's way of interpret negative argument. array[-1] always means the last element of an array, array[-2] denotes second last etc.

Upvotes: 1

Related Questions