Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sort an array alphabetically using sort_by in ruby?

I have an array of memberships. In each membership is a group. I need to sort this array of memberships by the name of the group. I've tried a bunch of different ways, and the latest way is this:

@memberships.sort_by! { |m| m.group.name } 

However, this doesn't sort by the name. It appears to be randomly sorting the array.

  • Membership belongs_to :group
  • Group has_many :memberships

@memberships is equal to:

[   {   id: 2141,   user_id: 491,   group_id: 271,   member_type: "member",     group: {       id: 271,       name: "Derek's",       privacy: "open",       bio_image_url: "/bio_images/medium/missing.png?1340285189",       member_count: 1,       upcoming_checkins_count: 0     }   },   {   id: 2201,   user_id: 221,   group_id: 291,   member_type: "member",     group: {       id: 291,       name: "Rounded Developement",       privacy: "closed",       bio_image_url: "/groups/medium/291/bioimage.jpg?1340736175",       member_count: 7,       upcoming_checkins_count: 0    } } ] 

NOTE: This does work --> @memberships.sort_by! { |m| m.group.id }

It will order the array based on the group.id so maybe it has something to do with sorting alphabetically?

Any help would be much appreciated.

like image 751
Brian Weinreich Avatar asked Jul 17 '12 21:07

Brian Weinreich


People also ask

How do I sort an array alphabetically?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.

How can you sort an array Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.

Can you sort elements in a Ruby hash object?

Sorting Hashes in RubyTo sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.

What sorting algorithm does Ruby use?

The Array#sort method in Ruby uses the venerable Quicksort algorithm. In its best case, Quicksort has time complexity O(n log n), but in cases where the data to be sorted is already ordered, the complexity can grow to O(n2).


1 Answers

Wow, after struggling with this for an extremely long time, I realized my problem was a simple one. I was sorting by group.name but some of the group names were uppercase and some were lower, which was throwing it all off. Converting everything to downcase worked well.

@memberships.sort_by!{ |m| m.group.name.downcase } 
like image 63
Brian Weinreich Avatar answered Oct 11 '22 14:10

Brian Weinreich