简体   繁体   中英

Ruby sorting arrays by grouping and sorting by number

Given an array like

['b1','a2','a3','b2','a1','b3']

How can i sort it so it groups by letter 'a' or 'b' then sorts these in order of the number present. eg.

['a1','a2','a3','b1','b2','b3']

or more complicated example:

['fb15', 'abc51', 'abc30', 'fb12']

which sorts to:

['abc30', 'abc51', 'fb12', 'fb15']

So hypothetically I could have a large group of different 'tags' like dog. cat, bear, owl. Which all appear in an array a number of times each, each time followed by a number.

Simply I want to group them and then sort by the number.

In Ruby, arrays are ordered lexicographically. That means, whenever you have a requirement that you need to order something by a primary, then a secondary, then a tertiary, … ordering key, you can simply convert your item into an array.

ary.sort_by do |el|
  str, num = el.partition(/\p{Digit}+/)
  [str, num.to_i]
end

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