在Rails中按字母顺序排序 [英] Sort alphabetically in Rails
本文介绍了在Rails中按字母顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何按Rails(字母顺序)对数组进行排序.我已经尝试过:
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?
推荐答案
您应该首先将每个字符串都转换为小写字母,然后进行如下排序:
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"]
这篇关于在Rails中按字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文