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

0
800

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.

Summary

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 = 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.

Solution

Can be found on the solutions branch on github.

LEAVE A REPLY

Please enter your comment!
Please enter your name here