0
0
Rubyprogramming~3 mins

Why Method declaration with def in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write a set of instructions once and use it anywhere in your program without repeating yourself?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
width = 5
height = 10
area = width * height
puts area

width = 7
height = 3
area = width * height
puts area
After
def area(width, height)
  width * height
end

puts area(5, 10)
puts area(7, 3)
What It Enables

It makes your code reusable and easier to understand, so you can build bigger programs without confusion.

Real Life Example

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.

Key Takeaways

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.