简体   繁体   English

如何使用 ruby 对嵌套的坐标数组进行排序

[英]How to sort an nested array of coordinates with ruby

I am trying to sort with ruby a nested array like this:我正在尝试使用 ruby 对嵌套数组进行排序,如下所示:

[[810, 266], [236, 236], [814, 820], [230, 800]]

Each array [x, y] means a position in a photo and I want to sort it so the first array in the nested array is the one in the top left, the second in the top right, the third in the bottom left and the last in the bottom right.每个数组[x, y]表示照片中的 position 并且我想对其进行排序,因此嵌套数组中的第一个数组是左上角的数组,右上角的第二个数组,左下角的第三个数组和最后在右下角。 The array will always be 4 arrays into one [[x,y],[x,y],[x,y],[x,y]] .该数组将始终是 4 arrays 到一个[[x,y],[x,y],[x,y],[x,y]]

input输入

[[810, 266], [236, 236], [814, 820], [230, 800]]

output output

[[236, 236], [810, 266], [230, 800], [814, 820]]

You can use sort_by to sort by y first (top to bottom) and x second (left to right):您可以使用sort_byy首先(从上到下)和x第二(从左到右)排序:

ary = [[810, 266], [236, 236], [814, 820], [230, 800]]

ary.sort_by { |x, y| [y, x] }
#=> [[236, 236], [810, 266], [230, 800], [814, 820]]

This works, because arrays are sorted in an element-wise manner, see Array#<=> .这是可行的,因为 arrays 以元素方式排序,请参阅Array#<=>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM