Can you create a nested array by combining two ranges?

Viewed 75

I am currently creating a Chess game, and I'm setting up an array for each chess piece which contains their legal move set. For example, a bishop can only move diagonally so the move set would need to be the following to move in a left upwards diagonal.

[[-1, -1], [-2, -2] ...repeated... [-7, -7], [-8, -8]]

Rather than having long lines of code for each direction, is there a way I can created a nested array with two range?

Eg:

([-1, -1])..([-8, -8])
2 Answers

Enumerable#zip combines two enumerations.

(-8..-1).zip(-8..-1).reverse
  # => [[-1, -1], [-2, -2], [-3, -3], [-4, -4], [-5, -5], [-6, -6], [-7, -7], [-8, -8]]

Maybe OT, but you can accomplish the same result with different approach, which could help with other chess pieces.

For example:

(1..8).map { |n| [-n, -n] }
#=> [[-1, -1], [-2, -2], [-3, -3], [-4, -4], [-5, -5], [-6, -6], [-7, -7], [-8, -8]]

Or also:

8.times.map { |n| [-n-1, -n-1] }
#=> [[-1, -1], [-2, -2], [-3, -3], [-4, -4], [-5, -5], [-6, -6], [-7, -7], [-8, -8]]
Related