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.
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.
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
Let's blur the end keyword a bit.Â
How much does it affect the way you read this code?
Those methods, if refactored to use the endless method, will look like this:
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: This is also a multi-line endless method and a valid Ruby syntax: 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.
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:
The endless method helps in defining predicates and naming scoped collections without adding extra lines of code.
Used to define computed attributes or predicates in this PORO object
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