Sort alphabetically in Rails

回眸只為那壹抹淺笑 提交于 2020-07-06 12:27:12

问题


How do I sort an array in Rails (alphabetical order). I have tried:

sort_by(&:field_name) 

which that gives me an array with capital letter order and then lower case order. I have tried:

array.sort! { |x,y| x.field_name.downcase <=> y.field_name.downcase }

Is there any way to solve this?


回答1:


You should first downcase every string and then sort like:

array = ["john", "Alice", "Joseph", "anna", "Zilhan"]
array.sort_by!{ |e| e.downcase }
=> ["Alice", "anna", "john", "Joseph", "Zilhan"]



回答2:


Be aware - names can contain special characters. These will be sorted to the end.

>> ["Ägidius", "john", "Alice", "Zilhan"].sort_by!{ |e| e.downcase }
=> ["Alice", "john", "Zilhan", "Ägidius"]

To cover this, you can use...

>> ["Ägidius", "john", "Alice", "Zilhan"].sort_by!{ |e| ActiveSupport::Inflector.transliterate(e.downcase) }
=> ["Ägidius", "Alice", "john", "Zilhan"]


来源:https://stackoverflow.com/questions/18441435/sort-alphabetically-in-rails

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