จัดการ grid ใน Ruby ด้วย Array#transpose แปลง rows ↔ columns
Columns The Hard Way
Grid 3x3:
grid = [[1,2,3], [4,5,6], [7,8,9]]
Row แรก: grid[0] # [1,2,3] Column แรกยาก: [grid[0][0], grid[1][0], grid[2][0]] # [1,4,7]
Columns The Easy Way
columns = grid.transpose columns[0] # [1, 4, 7] (column แรก!)
เพียงแค่ transpose!
Tic-Tac-Toe Application
เช็คชนะ: ต้องเช็ค rows, columns, diagonals
def check_rows
@board.each { |row| return row.first if all_equal?(row) }
end
def check_columns
@board.transpose.each { |row| return row.first if all_equal?(row) }
end
def all_equal?(row)
return if row.first == nil
row.each_cons(2).all? { |x,y| x == y }
end
แตกต่างแค่ transpose! รู้เมธอดมาก = ประหยัดงาน
Summary
transpose แปลง rows เป็น columns ใน perfect grid ใช้งานง่าย ประหยัดโค้ด