Sort a Collection of Struct Objects by One of Their Attributes in Ruby


In this guide we’ll examine how to implement the sort_by method in order to sort a collection of Ruby struct objects by a specific attribute.


Build a method that iterates over a collection of struct objects and sort them by a specific attribute.

Exercise File

Code File

Exercise Description

Given the following array of structs:

Invoice =, :total, :category)

google ='Google', 500, 'Marketing')
amazon ='Amazon', 1000, 'eCommerce')
yahoo ='Yahoo', 300, 'Marketing')

invoices = [google, amazon, yahoo]

Build out a method that sorts the objects by their total values.

Expected Output # 'Amazon' # 'Yahoo'

Real World Usage

Ruby’s sort_by method is a powerful, but underused method, that allows you to build custom sorting behavior. This is a feature you will be asked to build out on a regular basis as a Ruby developer.


Can be found on the solutions branch on github.


Please enter your comment!
Please enter your name here