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"]
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With