Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion content/open-source/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ This gem encapsulates a way of having a predefined set of properties within a te

Open Source library to apply Royal Mail Rules & Exceptions to PAF (Postcode Address File) addresses when converting to a printable format.

### [dvla-browser-drivers](https://github.com/dvla/dvla-browser-drivers)

This gem has pre-configured browser drivers that you can use out-of-the-box for the development of your automated test suite or application.

# Dynamics 365

### [dataverse-helper](https://github.com/dvla/dataverse-helper)
Expand All @@ -60,4 +64,4 @@ This gem helps you integrate with Microsoft Dynamics using Microsoft Dataverse W

### [postman-paf-js](https://github.com/dvla/postman-paf-js)

Open Source library to apply Royal Mail Rules & Exceptions to PAF (Postcode Address File) addresses when converting to a printable format.
Open Source library to apply Royal Mail Rules & Exceptions to PAF (Postcode Address File) addresses when converting to a printable format.
33 changes: 33 additions & 0 deletions content/posts/2024-12-using-max-by-in-ruby/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
author: "Tomos Griffiths"
title: "TiL: Using the max_by method in Ruby"
description: "Using max_by to filter out data based on the highest value for a particular field"
draft: false
date: 2025-02-20
tags: ["Ruby", "max_by", "Testing", "Today I Learned"]
categories: ["TIL", "Ruby", "max_by", "Testing"]
ShowToc: true
TocOpen: true
---

When trying to get an upper or lower value for a certain field in an object can be cumbersome. But when using the `max_by` method, this can actually be done quite elegantly. For example:

```ruby
persons = [
{ "name" => "John McJohnson","age" => 34, "topScoreAtBowling" => 205},
{ "name" => "Davey Jones","age" => 304, "topScoreAtBowling" => 300},
{ "name" => "Willy Wonka","age" => 50, "topScoreAtBowling" => 200}
]
```

If we had a bowling competition and wanted to see who had the `topScoreAtBowling` field, rather than looping through the array and looking at each object, we can simply use the `max_by` command as follows:

```ruby
persons.max_by { |person| person['topScoreAtBowling']} #{"name"=>"Davey Jones", "age"=>304, "topScoreAtBowling"=>300}
```

The resultant object would be returned, and could be processed into their "Hall of Fame"!

## Conclusion

The `max_by` method is very convenient when dealing with a large array of objects, and you are required to find the highest value for a certain field. Alternatively the `min_by` method can be used to find the lower value of a certain field