Skip to main content

Ruby: Sort an array of objects by an attribute

·174 words·1 min· ·
General Features Ruby
Ariejan de Vroom
Author
Ariejan de Vroom
Jack of all Trades, Professional Software Craftsman

In this example I’ll show you how easy it is to sort an array of (the same kind of) objects by an attribute. Let’s say you have an array of User objects that have the attributes ’name’ and ’login_count’. First, find all users.

@users = User.find(:all)

Now, we have to sort this array by ’name’. Since we don’t know if any user used capitals in his name or not, we use ‘downcase’ to sort without case sensitivity.

A small not. ‘sort’ returns a new array and leaves the original unchanged. You may want to just reorder the @users array, so use the ‘sort!’ method. The ‘!’ indicates it’s a destructive method. It will overwrite the current @users array with the new sorting.

@users.sort! { |a,b| a.name.downcase <=> b.name.downcase }

That’s all! Since strings are comparable, this will sort you user objects alphabetically by name. Want to sort on login_count instead?

@users.sort! { |a,b| a.login_count <=> b.login_count }

So, now you can easily sort any object in an array just like you want it too!

Related

New in Rails: Resource Scaffold Generator
·214 words·2 mins
General RubyOnRails Features
Rails: Nested resource scaffold
·487 words·3 mins
General Everything Features
Why Ruby Rocks - Convince your fellow developers
·99 words·1 min
General Everything Blog Ruby