Why no for loops in Ruby?

In the section on iteration, it brings up for loops only to say that they aren’t recommended for use in Ruby. Is this just because you can use iterators instead, or is there some technical reason for this?

My understanding is that there are some technical nuances dealing with scope and blocks that make enumeralble methods preferable to for loops in some cases, but the main reason is style. Ruby prioritizes readability by abstracting away technical implementation details and focusing on higher level intent wherever possible.

sure, I could say:

words = %w(ruby is awesome)

for i in 0...words.length
    puts words[i]
end

and that’s fine. But it’s not clear from the for loop itself that my intent is to print each word in my array, I have to do some additionally thinking to realize that. Also, there’s some extra baggage in there that I don’t need: I don’t need the indices of the array here, so why am I keeping track of them?

words.each { |word| puts word }

With the each iterator it’s abundantly clear what my actual intent is: to print each word in my words array. It almost reads like english.

Say I wanted to do some operation a 10 times, sure I could say:

for i in 0..9
    puts "Hi!"
end

But by using the times method, it’s instantly clear that my goal is to puts “Hi!” 10 times.

10.times { puts "Hi! }

So there’s nothing wrong with a for loop, it’s just not very rubyish. In almost every situation that you could use a for loop, there’s a way to make your intent more clear and code it with less unnecessary baggage.

3 Likes