Using a Language-Dependent Sort Function in Ruby / Rails

What is a good approach for sorting an array of strings according to the current locale?

For example, the standard Array#sortplaces “Ä” after “Z”, which is incorrect in German.

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

Google did not help me this time. Can you?

Any advice appreciated!

+3
source share
1 answer

There are two general questions:

  • Sort by database (optimus)

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

  • Non-localize the special character to order: "Äððß" .uncolate => "Andos"

you add an unnecessary function to a string and use for sorting maybe

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

And sorting:

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

I hope this helps

+2
source

Source: https://habr.com/ru/post/1741739/


All Articles