Using a locale-dependent sorting function in Ruby/Rails
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!
There are two common aproaches:
Sort with your database (optimus)
or, if you absolutely need to do something with ruby before sorting:
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
精彩评论