Loops in Ruby — Teaching Your Code to Repeat
CodeCraft Diaries #4: Loops in Ruby — Teaching Your Code to Repeat
"Why did the Ruby developer go in circles? Because they couldn't break the loop!"
Welcome back, CodeCrafters! 🎉 In our last adventure, we taught our code to make decisions using control flow. Now, it's time to teach it to repeat tasks efficiently. Let's dive into the world of loops in Ruby!
🔁 The Need for Loops
Imagine you want to print "Hello, World!" five times. You could write:
puts "Hello, World!"
puts "Hello, World!"
puts "Hello, World!"
puts "Hello, World!"
puts "Hello, World!"
But that's not efficient. Instead, let's use a loop:
5.times do
puts "Hello, World!"
end
Much better, right?
🌀 Types of Loops in Ruby
1. while Loop
Repeats as long as a condition is true.
i = 0
while i < 5
puts "i is #{i}"
i += 1
end
2. until Loop
Repeats until a condition becomes true.
i = 0
until i == 5
puts "i is #{i}"
i += 1
end
3. for Loop
Iterates over a range or collection.
for i in 0..4
puts "i is #{i}"
end
4. each Iterator
Preferred way to iterate over collections.
[1, 2, 3, 4, 5].each do |number|
puts "Number is #{number}"
end
⚠️ Loop Control: break and next
Control the flow within loops using:
break: Exit the loop early.next: Skip to the next iteration.
i = 0
while i < 10
i += 1
next if i % 2 == 0
break if i > 7
puts i
end
💡 Pro Tip
Always ensure your loops have a terminating condition to avoid infinite loops. Your future self will thank you!
🎯 TL;DR
- Use loops to perform repetitive tasks efficiently.
- Choose the right loop type based on your needs.
- Control loop execution with
breakandnext.
Stay tuned for our next post, where we'll explore methods and how to DRY (Don't Repeat Yourself) up your code!
Happy Coding! 🚀
Comments
Post a Comment