Ruby language based sorting function

For my application (Ruby on Rails) I have a window for selecting a country for the registration page. These countries are localized in different languages. But I could not find a way to sort them based on the language in which it is localized. Currently, I have parsed it in English only. Is there a way to sort country names by language? that is, the order of countries should change (in ascending order) in accordance with the localized language. Thank..

+3
source share
3 answers

You can create your own comparison method Stringbased on this alphabet, something like this (works in Ruby 1.9):

class String
  # compares two strings based on a given alphabet
  def cmp_loc(other, alphabet)
    order = Hash[alphabet.each_char.with_index.to_a]

    self.chars.zip(other.chars) do |c1, c2|
      cc = (order[c1] || -1) <=> (order[c2] || -1)
      return cc unless cc == 0
    end
    return self.size <=> other.size
  end
end

class Array
  # sorts an array of strings based on a given alphabet
  def sort_loc(alphabet)
    self.sort{|s1, s2| s1.cmp_loc(s2, alphabet)}
  end
end

array_to_sort = ['abc', 'abd', 'bcd', 'bcde', 'bde']

ALPHABETS = {
  :language_foo => 'abcdef',
  :language_bar => 'fedcba'
}

p array_to_sort.sort_loc(ALPHABETS[:language_foo])
#=>["abc", "abd", "bcd", "bcde", "bde"]

p array_to_sort.sort_loc(ALPHABETS[:language_bar])
#=>["bde", "bcd", "bcde", "abd", "abc"]

, .

+3

- twitter , Ruby https://github.com/twitter/twitter-cldr-rb#sorting-collation. , , , . git://github.com/k3rni/ffi-locale.git, .

+1

, .

-1

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


All Articles