Image of Lucian Ghinda writing for notes.ghinda.com
June 6th, 2024

Endless Method - a short summary

Did you know Ruby 3.0 introduced the endless method? That was more than three years ago.

It could be helpful sometimes for writing concise code!

Let me show some use cases and see how it can improve code readability and structure.

Endless method official syntax
Endless method official syntax

Before we begin, let's clarify: I'm not saying the endless method is better than traditional methods, nor that it could fit any case. 

I am more interested in exploring how it can change the code shape. 

One-line methods were possible in Ruby even before the endless method 

Here are some examples of valid #Ruby syntax.

one-liners in Ruby
one-liners in Ruby

Do we really need the end keyword to know a method is finished after the closing bracket?

My assertion is that in these examples we don't need the end keyword to mentally know where the body of those methods ends

Do we really need the end?
Do we really need the end?

Let's blur the end keyword a bit. 

How much does it affect the way you read this code?

Normal methods with blurry end
Normal methods with blurry end

Those methods, if refactored to use the endless method, will look like this:

endless method examples
endless method examples

The endless method is defined as a "single expression," not a single line.

This means you can write multi-line endless methods, so let's explore two examples:
multi line endless method in Ruby
multi line endless method in Ruby
This is also a multi-line endless method and a valid Ruby syntax:
a multi line case as endless method
a multi line case as endless method
Why use the endless method?

In some cases, It's efficient and doesn't add more lines of code, making it perfect for defining computed attributes, predicates, and improving readability through naming.

Why use the endless method
Why use the endless method

Let's look at a real-world example from the open-source Keygen API where they are using it to write computed attributes, predicated and name statements to increase readability:

Reasons to use it
Reasons to use it

The endless method helps in defining predicates and naming scoped collections without adding extra lines of code.

Keygen API code sample
Keygen API code sample

Used to define computed attributes or predicates in this PORO object

Keygen API code sample
Keygen API code sample

Are you using the endless method in your Ruby codebase?

I wrote all of this with more examples and explanations about when and how to use the endless method in this article https://allaboutcoding.ghinda.com/endless-method-a-quick-intro