Sort array of strings with special characters

时光怂恿深爱的人放手 提交于 2019-12-24 00:17:29

问题


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

I have:

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

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


回答1:


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(...)

An alternative would be to use the sort_alphabetical gem.




回答2:


here's my approach:

class String
  def to_canonical
    self.gsub(/[áàâãä]/,'a').gsub(/[ÁÀÂÃÄ]/,'A')
  end
end

['Água', 'Electricidade', 'Telefone', 'Internet', 'Televisão', 'Gás', 'Renda'].sort {|x,y| x.to_canonical <=> y.to_canonical}

this proves to be usefull for other regexp aswell, the to_canonical method can be implemented they way that best suits you, in this example just covered those 2 regexp.

hope this alternative helps. :)



来源:https://stackoverflow.com/questions/6099097/sort-array-of-strings-with-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!