0

I have a column in my table that are codes. They are in the format of AAA-XXXX-YYY where

  • AAA is Alphabetical
  • XXX is Numeric
  • YYY is Numeric

I want to use an alphabetical sort on AAA, then numeric sort on XXXX, then numeric sort on YYY for my default_scope so when I index them they are sorted like that.

If I did an alphanumeric sort on the column I would end up with the following:

AAA-1000-1
AAA-1000-111
AAA-1000-2
BB-1000-12
BBB-1000-1
BCA-1000-1
C-1000-12

but 111 is bigger than 2 using a numeric sort.

EDIT:AAA is not fixed in length. So it could be "AA" or "BBBB" or "CCC". There has been mention of using SQL SUBSTRING but the position is not always set.

EDIT2: I probably should mention this sort needs to be done on a default_scope so when I access Object.all they are by default sorted this way.

Thanks for your help!

  • 4
    http://stackoverflow.com/questions/5480703/how-to-sort-an-alphanumeric-array-in-ruby – Unixmonkey Dec 17 '12 at 14:48
  • http://stackoverflow.com/questions/4785424/how-to-order-by-certain-part-of-a-string for table sorting based on substrings in MySQL – mccannf Dec 17 '12 at 16:44

1 Answers1

0
arr = ['AAA-1000-1','AAA-1000-111','AAA-1000-2','E-3-3','E-2-3','CCCC-2-45']

arr.sort_by {|elm| "%10s%10i%10i" % elm.split('-') }

=> ["E-2-3", "E-3-3", "AAA-1000-1", "AAA-1000-2", "AAA-1000-111", "CCCC-2-45"] 
Pritesh Jain
  • 9,106
  • 4
  • 37
  • 51
  • How do I get this to run within default_scope. And how do I get the first section to sort alphanumerically. Meaning the following: A, AA, BBB, C, D1, D1A, DA, DB3, DBB – user1910255 Dec 20 '12 at 17:08
  • And also a follow up, how about sorting by the middle section first, then first section, then third section? Thanks in advance! – user1910255 Dec 20 '12 at 17:21