Discover how to save time and keep your code neat by calling methods without making objects!
Why Class methods with self prefix in Ruby? - Purpose & Use Cases
Imagine you have a recipe book and you want to write down a method to calculate the total cooking time for any recipe. Without class methods, you'd have to create a new recipe instance every time just to use that calculation, even if you don't need to store any recipe details.
Manually creating an object just to use a method wastes time and memory. It feels like making a whole cake just to taste a single ingredient. This slows down your program and makes your code messy and confusing.
Using class methods with the self prefix lets you call methods directly on the class itself, without making an object. It's like having a kitchen timer that works independently, so you can quickly get the cooking time without extra steps.
recipe = Recipe.new recipe.total_cooking_time(ingredients)
Recipe.total_cooking_time(ingredients)
It enables quick, clear access to utility functions related to the class without unnecessary object creation.
Think of a Math module where you want to calculate the square root. You don't need a math object, just call Math.sqrt(number) directly.
Class methods let you call functions on the class itself.
They avoid the need to create objects when not necessary.
This makes your code cleaner and faster.