Dillon Barker
Dillon Barker

Reputation: 80

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.

Upvotes: 0

Views: 117

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369574

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

Upvotes: 6

Related Questions