Because Copy-Pasting Is Not Coding - Ruby Loops Tutorial
Loops in Ruby — Because Repeating Manually Is So 2000s
Imagine being told to print “I love Ruby” 100 times by hand. Sounds painful, right? Well, that’s what we used to do before loops existed (not really, but you get the point 😉). In today’s edition of CodeCraft Diaries, we’ll explore the magic of loops in Ruby — tools that make repetition effortless, elegant, and DRY (Don’t Repeat Yourself).
Why Loops Matter
Loops allow your code to execute a block repeatedly based on a condition or a set number of times. They're essential when you're handling lists, user input, data processing, and more.
1. while
Loop
The while
loop runs as long as the condition is true
.
i = 0
while i < 5
puts "Looping... #{i}"
i += 1
end
Common mistake:
Forgetting to increment the loop variable, which causes an infinite loop.
2. until
Loop
Think of until
as the opposite of while
— it runs until the condition becomes true
.
i = 0
until i == 5
puts "Counting up: #{i}"
i += 1
end
3. for
Loop
Less common in idiomatic Ruby but still useful.
for i in 1..3
puts "Iteration ##{i}"
end
4. Looping with .each
Rubyists love each
for iterating over arrays and hashes.
["apple", "banana", "cherry"].each do |fruit|
puts "I love #{fruit}"
end
5. times
Loop
When you know exactly how many times to repeat something.
3.times do
puts "Keep it DRY!"
end
6. Loop Control: break
, next
, and redo
These help you manage the flow inside your loops.
i = 0
while i < 10
i += 1
next if i % 2 == 0 # Skip even numbers
break if i > 7 # Exit early
puts i
end
🤦 Common Beginner Mistakes
- Not updating the loop variable (infinite loop warning!)
- Using
for
wheneach
is more readable - Trying to break from
each
improperly (usebreak
inside the block)
🎯 How Loops Make Your Code DRY
Loops help you avoid writing repetitive code. Combined with methods in Ruby, they turn verbose code into elegant solutions.
Compare This:
# Without loop
puts "Hi"
puts "Hi"
puts "Hi"
With This:
3.times { puts "Hi" }
🚀 Want More Ruby Wizardry?
Check out previous posts:
And don’t miss the next CodeCraft Diary: “Data Types in Ruby — Because Everything Has a Type”
📌 Key Takeaways
- Loops automate repetition and save time.
- Ruby supports multiple looping constructs:
while
,until
,for
,each
,times
. - Use
break
,next
, andredo
to control loop behavior. - Loops are a cornerstone of writing DRY, clean code.
Comments
Post a Comment