问题
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