nisha
nisha

Reputation: 63

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?

Upvotes: 5

Views: 11018

Answers (2)

lual
lual

Reputation: 446

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"]

Upvotes: 4

Aman Garg
Aman Garg

Reputation: 4218

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"]

Upvotes: 15

Related Questions