Unleashing Ruby Methods: Write Less, Do More ๐
๐ CodeCraft Diaries #4: Methods in Ruby — DRY Up That Code!
"Copy-paste is not a strategy. Reuse is."
So far in our Ruby journey, you've seen variables, data types, and how to make decisions with control flow. Now it's time to explore the most powerful tool in your dev toolkit:
๐ Methods — Your Code’s Superpower
Think of a method as your personal code assistant.
Instead of repeating the same logic over and over, you wrap it in a neat little function (method) and call it whenever you need it.
๐ฆ Defining a Method
Here’s how you define a method in Ruby:
def greet
puts "Hello there!"
end
Now just call it:
greet # Output: Hello there!
Simple, right? But wait, there’s more…
๐ฏ Methods with Parameters
Want to greet someone by name?
def greet(name)
puts "Hello, #{name}!"
end
greet("Ruby") # Hello, Ruby!
greet("Nora") # Hello, Nora!
Now your code is dynamic and reusable! ๐
๐ Return Values
Methods can give back results using return
(although Ruby often returns the last expression by default):
def add(a, b)
return a + b
end
sum = add(5, 3)
puts sum # 8
๐ฅ Why Use Methods?
- ✅ Avoid repetition (DRY: Don’t Repeat Yourself)
- ✅ Make code readable and organized
- ✅ Reuse logic with different values
๐งช Example: A Tiny Calculator
def calculator(a, b, operation)
if operation == "add"
a + b
elsif operation == "subtract"
a - b
else
"Unsupported operation"
end
end
puts calculator(10, 5, "add") # 15
puts calculator(10, 5, "subtract") # 5
Want to extend it to multiply, divide, or find square roots? You totally can.
✨ Pro Tip
“If you find yourself copy-pasting more than once, turn it into a method.”
Let your methods be the reusable Lego bricks of your codebase ๐งฑ
⏭ Up Next on CodeCraft Diaries:
Loops in Ruby — Because Repeating Manually Is So 2000s
We’ll dive into each
, while
, and the mighty times
loop in Ruby.
๐ Missed the Last Blog?
Check out Control Flow in Ruby — Teaching Your Code to Make Decisions
Keep building, keep crafting — one line at a time ๐ป
Comments
Post a Comment