Kerby82
Kerby82

Reputation: 5146

Way to order alphanumeric string

I have a series of model objects with the following values on a column:

I would like to query the db and get the result in alphanumeric order. I would like to obtain the result in this order:

Instead, I obtain the following order:

Any smart way to achieve that result directly with active record?

Upvotes: 0

Views: 469

Answers (1)

John Skiles Skinner
John Skiles Skinner

Reputation: 2028

Here I'm re-stating your example data as an array:

example_array = %w{2018-A-1 2018-A-10 2018-A-2 2018-A-100 2018-A-11 2018-B-1 2018-B-10 2018-B-2 2018-B-100 2018-A-11}

It's not perfectly clear to me what order you're trying to get. If you are trying to sort based only on the digits following the final hyphen, this should work:

example_array.sort_by{|e| e.split("-").last.to_i }

If you also intend to include the letter before the final number, perhaps this is what you want:

example_array.sort_by{|e| [e.split("-")[-2], e.split("-").last.to_i] }

Upvotes: 1

Related Questions