views:

95

answers:

1

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!

+2  A: 

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

Fer
Thanks, this seems to be a good start!
knuton
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/9YnosRHave a look at it and you may save some work :)
Fer
Didn’t notice your comment until just now. Thanks!
knuton