3

What is a good approach to sorting an array of strings in accordance with the current locale?

For example the standard Array#sort puts "Ä" after "Z", which is not correct in German.

I would have expected the gem I18n to offer a hook for defining my own sorting algorithms or providing collation strings or objects. In my imagination, passing this proc or string to the sort function, would make it behave as necessary. I know that this is possible in Python, for example.

Google has not helped me this time. Can you?

Any advice appreciated!

knuton
  • 3,537
  • 3
  • 24
  • 23

1 Answers1

2

There are two common aproaches:

  1. Sort with your database (optimus)

    or, if you absolutely need to do something with ruby before sorting:

  2. Unlocalize special character for ordering: "Äñðøß".uncolate => "Andos"

you add an uncolate function to string and use for sorting uncolate can be

class String
  def uncolate
    self.tr(SPECIAL_CHARS,SUBSTITUTE_CHARS)
  end
end

And sort:

international_things.sort_by{|i| i.international_attr.uncolate}

I hope it helps

Community
  • 1
  • 1
Oinak
  • 1,805
  • 1
  • 12
  • 13
  • 2
    Recently, you got this twitted by rails I18n devs: @svenfuchs: assert_equal "AEroskobing", I18n.backend.transliterate(:foo, "Ærøskøbing") http://bit.ly/aTUx7J http://bit.ly/9YnosR Have a look at it and you may save some work :) – Oinak May 03 '10 at 11:41
  • Didn’t notice your comment until just now. Thanks! – knuton Jun 10 '10 at 13:10
  • @Oinak, I think it's just `I18n.transliterate(...)`. – pablo Sep 25 '14 at 23:37