Lens: What causes this repeat pattern in an image? (by rearranging your pixels by their intensity, code included)

Just out of curiosity, I was playing with RGB coordinates and image pixels. Then, for some reason, I decided to get all the pixels in an image, get the RGB coordinates / values ​​of each pixel (for example, RGB (120, 30, 15)), add the coordinates together (for example, 120 + 30 + 15 = 165), and then sort the pixels in ascending order according to that number (the sum of the RGB coordinates / pixel values).

So, in order to visualize that, I "printed" the pixels in another image of the same dimensions as the original, but with the pixels rearranged as content. See an example below (and the Ruby code for it).

You will notice that the output image has a very well defined pattern. I tried the same thing (rearranging the pixels by R + G + B) with many different images, and there is always a similar pattern of repeating smaller versions of the same image.

Why does that happen? What explains the pattern of the image when the pixels are rearranged?

Original Image:
enter the description of the image here

Image with rearranged pixels:
enter the description of the image here

# Ruby code
require 'rmagick'
include Magick

img = ImageList.new("images/test-image.jpg")
pixels = img.get_pixels(0,0,img.columns,img.rows)

# Sort pixels by total intensity
pixels = pixels.sort {|p| p.red + p.green + p.blue}

out_img = Magick::Image.new(img.columns, img.rows)
out_img.store_pixels(0,0, img.columns, img.rows, pixels)

@ cthom06 found out in the comments. The code above is using sort instead of sort_by to sort the pixel matrix. Still curious about what sort is doing.

When you wear sort_by, the output image looks like this:
enter the description of the image here