class MatrixSorter attr_reader :matrix def initialize(matrix) @matrix = matrix end def sort! @matrix = matrix.flatten.sort.each_slice(matrix.size).to_a end end array = [[1, 2, 3], [4, 1, 0], [7, 7, 6]] matrix_sorter = MatrixSorter.new(array) matrix_sorter.sort! p matrix_sorter.matrix.inspect
I absolutely do not remember how to properly sort the two-dimensional array. In this I did as I realized: we sort all the lines, and then we compare the lines to each other by the first element.
Since ruby is, after all, an object-oriented language, sorting is performed as a class. Input also missed, because there were no questions about him. Sort by manual rearrangement of elements in ruby is not worth it. All this language is able itself, and native sortings are optimized.
Honestly, I have very little idea what needs to be further explained here. So ask in comments - I will add the answer. And if you need a manual sorting for some reason, just write in the comments - I will add a solution.
UPD .:
I'm not quite sure that the two-dimensional array is sorted in this way, but I changed the example so that it is sorted in this way. The principle of such a flatten - converts an array into a one-dimensional, sort - sorts it, each_slice(matrix.size) splits into groups, each by matrix.size (we assume that the array is "square"). And since each_slice returns an object of the Enumerator class, we convert it back to an array.
Unfortunately, the code is difficult to read. But I think the problem is this:
array3 [i] [j], array3 [i + 1] [j + 1] = array3 [j + 1] [i + 1]
On the left side there are two variables, on the right there is only one.
- matrix.sort! {| arr1, arr2 | arr1.first <=> arr2.first} - the
sort method can take as its argument a block that is executed during the sorting process.
Since a two-dimensional array is, in fact, an array of arrays, we first sorted each array. (&:sort!) is an abbreviated (and preferred) form. Completely, it would look like matrix.each {| array | array.sort! }
four.
And in the first passage of your code, too, the function does not understand itself, or the sort method is called! for class Array?
This is not understood at all. First, create an object of the MatrixSorter class and then call the method defined in this sort! class sort! . Which, inside, calls the standard array methods.
sortorsort!unsuitable? - anoam