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

查看:63
本文介绍了使用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和linux运行ruby 1.9.2和Rails 3.0.5。

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) }

其中哪个返回正确的结果:

Which returns the correct result:

=> ["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...

Update

这不是完美的:(它在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天全站免登陆