用特殊字符对字符串数组进行排序 [英] Sort array of strings with special characters

查看:54
本文介绍了用特殊字符对字符串数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 3 中,如何对带有特殊字符的字符串数组进行排序.

In Rails 3 how do I sort an array of strings with special characters.

我有:

[Água, Electricidade, Telefone, Internet, Televisão, Gás, Renda]

但是,当我对数组调用 sort 时,Água 会被发送到数组的末尾.

However when i invoke sort over the array Água gets sent to the end of the array.

推荐答案

我遇到同样问题时使用的方法(取决于 iconv gem):

The approach I used when I ran into the same issue (depends on iconv gem):

require 'iconv'

def sort_alphabetical(words)
  # caching and api-wrapper
  transliterations = {}

  transliterate = lambda do |w|
    transliterations[w] ||= Iconv.iconv('ascii//ignore//translit', 'utf-8', w).to_s
  end

  words.sort do |w1,w2|
    transliterate.call(w1) <=> transliterate.call(w2)
  end
end

sorted = sort_alphabetical(...)

另一种方法是使用 sort_alphabetical gem.

An alternative would be to use the sort_alphabetical gem.

这篇关于用特殊字符对字符串数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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