February 10 - 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.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise
Video locked
This video is viewable to users with a Bottega Bootcamp license

Summary

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

Exercise Description

Given the following array of structs:

Invoice = Struct.new(:name, :total, :category)

google = Invoice.new('Google', 500, 'Marketing')
amazon = Invoice.new('Amazon', 1000, 'eCommerce')
yahoo = Invoice.new('Yahoo', 300, 'Marketing')

invoices = [google, amazon, yahoo]

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

Expected Output

invoices.first.name # 'Amazon'
invoices.last.name # '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.

Test Cases

Code File