使用 Ruby/Rails 中的特定排序规则对值进行排序 [英] Sort values using a specific collation in Ruby/Rails

查看:23
本文介绍了使用 Ruby/Rails 中的特定排序规则对值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Ruby 中使用特定的排序规则对值数组进行排序?我需要根据 da_DK 排序规则进行排序.

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.

鉴于数组 %w(Aarhus Aalborg Assens) 我想返回正确的 ['Assens', 'Aalborg', 'Aarhus']用丹麦语订购.

Given the array %w(Aarhus Aalborg Assens) I would like to have ['Assens', 'Aalborg', 'Aarhus'] back which is the correct order in Danish.

标准排序方法

%w(Aarhus Aalborg Assens).sort

返回类似于 ascii 顺序的东西(至少不是丹麦顺序):

returns something that looks like the ascii order (at least not the Danish order):

["Aalborg", "Aarhus", "Assens"]

环境是 Snow Leopard 和运行 ruby​​ 1.9.2 和 Rails 3.0.5 的 linux.

The environment is both Snow Leopard and linux running ruby 1.9.2 and Rails 3.0.5.

推荐答案

我找到了 ffi-locale 在 Github 上,据我所知,这解决了我的问题.

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

它允许以下代码:

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

返回正确的结果:

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

我还没有调查性能,但它调用了本机代码,所以它应该比 Ruby 字符替换代码更快......

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

更新
它并不完美:(它在 Snow Leopard 上无法正常工作 - 似乎 strcoll 函数在 OS X 上已损坏并且已经有一段时间了.这对我来说很烦人,但主要的部署平台是 linux - 它可以工作的地方- 所以这是我目前首选的解决方案.

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.

这篇关于使用 Ruby/Rails 中的特定排序规则对值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆