Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort alphabetically in 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?

like image 303
nisha Avatar asked Aug 26 '13 09:08

nisha


2 Answers

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"]
like image 142
Aman Garg Avatar answered Nov 09 '22 00:11

Aman Garg


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"]
like image 30
lual Avatar answered Nov 08 '22 23:11

lual