简体   繁体   中英

How to sort array elements in lexicographic order in Ruby

I have an array

arr = [[1,2],[2,3],[2,1],[0,1]]

I would like them to be in order:

arr = [[0,1],[1,2],[2,1],[2,3]]

I would like to use Ruby's sort_by method to do this. How could I sort an array of arrays on two levels in Ruby like this?

Array#sort sorts sub-arrays lexicographically by default (see Array#<=> ). You don't need to define anything:

[[1,2],[2,3],[2,1],[0,1]].sort
# => [[0, 1], [1, 2], [2, 1], [2, 3]]

If you really want to use sort_by :

[[1,2],[2,3],[2,1],[0,1]].sort_by(&:itself)
# => [[0, 1], [1, 2], [2, 1], [2, 3]]

If you consider each element of the subarray to be a digit from 0 to 9, you could use Array#sort_by , where the block converts the array into string then into integer:

arr.sort_by { |e| e.join.to_i }

#=> [[0, 1], [1, 2], [2, 1], [2, 3]]


How it works.

 [1, 2].join #=> "12" [1, 2].join.to_i #=> 12 


In this case:

 arr = [[1,0,2,0],[2,3],[2,1],[0,1]] #=> [[0, 1], [2, 1], [2, 3], [1, 0, 2, 0]] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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