Unleashing Ruby Methods: Write Less, Do More ๐Ÿ”

๐Ÿš€ CodeCraft Diaries #4: Methods in Ruby — DRY Up That Code!

๐Ÿš€ 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

Popular posts from this blog

Why Every Developer Should Meet Ruby: A Friendly Introduction

This is Ruby. And Ruby knows how to block — like a bouncer for bad code. ๐Ÿ”ฅ

Iterators in Ruby — Think Less Looping, More Logic