Ruby array selective slice

I am slowly learning Ruby (at the moment, perhaps the first language I have invested so much time in learning), so this is likely to be a very simple question for many of you.

My toy project for my studies is mainly rogueli. Currently, I have a Map class that contains an array of Tile objects, representing, of course, each plate on the entire map. I am trying to create a method that will return a smaller array (the most likely example would be displaying the currently displayed area of ​​the map).

My problem boils down to this. Since the array containing all these fragments is one-dimensional, I cannot imagine a clean way to cut fragments of this array based on the two x, y coordinates that the method accepts to determine what needs to be returned. In other words, I cannot find a clean way to translate between two coordinate pairs without any rather ugly code, and I understand that there is a very simple way to do this, just by not “clicking”.

Anyone ideas? I am open to some pretty crazy offers!

+3
source share
2 answers

If your array is a single size, you can map the x and y coordinates to the index of the array in the same way as the pixels in the vga buffer.

offset = y * buffer_width + x

100 , 5,5, 5 * 100 + 5 = 505 ​​ 1- .

, . , 10x10 : 10 , buffer_width, , 10 , 10 10x10.

5 3x3:

buffer = ['0,0', '1,0', '2,0', '3,0', '4,0',
          '0,1', '1,1', '2,1', '3,1', '4,1',
          '0,2', '1,2', '2,2', '3,2', '4,2',
          '0,3', '1,3', '2,3', '3,3', '4,3',
          '0,4', '1,4', '2,4', '3,4', '4,4']

buffer_width = 5
buffer_height = 5

# now lets say we want to grab a 3x3 slice from right 
# in the middle of the array from 1,1->3,3

x1,y1 = 1,1
x2,y2 = 3,3

view_width = x2 - x1
view_height = y2 - y1

(0..view_height).each do |row|
  offset = (y1 + row) * buffer_width + x1
  puts buffer[offset..offset+view_width].inspect
end

:

["1,1", "2,1", "3,1"]
["1,2", "2,2", "3,2"]
["1,3", "2,3", "3,3"]

, .

, .

+4

.

a = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
a[1..2].map { |row| row[0..1] }

= > [[ "d", "e" ], [ "g", "h" ]]

+2

Source: https://habr.com/ru/post/1712656/