Reputation: 168101
Most of the time when I see a for
loop used in Ruby, the person who wrote it does not know Ruby well. Usually, it is much more readable when a for
loop is replaced by an iterator taking a block such as each
.
Is there any use-case where for
cannot be easily rewritten by an iterator with a block, or there is an advantage in using for
?
Is it true that for
is faster than an iterator method because for
is a keyword? What is the purpose of for
?
Upvotes: 3
Views: 101
Reputation: 53038
The block syntax is generally preferred by Ruby community.
There is a small difference in variable scope while using for
or each
.
Variable declared within a for
loop will be available outside the loop, where as those within an each
block are local to the block and will not be available outside it.
Upvotes: 3
Reputation: 106882
I saw the for
loop a lot in Rails books 6-8 years before. But is not preferred anymore.
There is a difference in the scope of the iterator variable. Take the following example:
numbers = [1, 2, 3]
numbers.each do |n|
# do nothing
end
begin
puts n
rescue Exception => e
puts e.message
end
for n in numbers do
# do nothing
end
puts "still: #{n}"
That would have this output:
# undefined local variable or method `n' for main:Object
# still: 3
Upvotes: 4