Sort values using a specific collation in Ruby/Rails

前端 未结 2 1860
忘了有多久
忘了有多久 2021-01-02 01:14

Is it possible to sort an array of values using a specific collation in Ruby? I have a need to sort according to the da_DK collation.

Given the array %w(Aarhu

2条回答
  •  生来不讨喜
    2021-01-02 01:38

    I found the ffi-locale on Github and that solves my problem as far as I can see.

    It allows the following code:

    FFILocale::setlocale FFILocale::LC_COLLATE, 'da_DK.UTF-8'
    %w(Aarhus Aalborg Assens).sort { |a,b| FFILocale::strcoll(a, b) }
    

    Which returns the correct result:

    => ["Assens", "Aalborg", "Aarhus"]
    

    I haven't investigated performance yet but it calls out to native code so it ought to be faster that Ruby character replacement code...

    Update
    It is not perfect :( It does not work properly on Snow Leopard - it seems that the strcoll function is broken on OS X and have been for some time. It is annoying to me but the main platform for deployment is linux - where it works - so it is my currently preferred solution.

提交回复
热议问题