What if you could write a set of instructions once and use it anywhere in your program without repeating yourself?
Why Method declaration with def in Ruby? - Purpose & Use Cases
Imagine you need to repeat the same set of instructions many times in your program, like calculating the area of different rectangles by writing the formula again and again.
Writing the same code repeatedly is slow and tiring. It's easy to make mistakes or forget to update all places if the formula changes. This makes your program messy and hard to fix.
Using a method lets you write the instructions once with def. Then you just call the method whenever you need it, keeping your code clean and easy to manage.
width = 5 height = 10 area = width * height puts area width = 7 height = 3 area = width * height puts area
def area(width, height) width * height end puts area(5, 10) puts area(7, 3)
It makes your code reusable and easier to understand, so you can build bigger programs without confusion.
Think of a recipe you use often. Instead of writing all steps every time you cook, you just say the recipe name. Methods work the same way in programming.
Writing repeated instructions manually is slow and error-prone.
Methods let you write code once and reuse it easily.
This keeps your program clean, simple, and easy to update.