Ruby has support for the for i in a
syntax, but no one really uses it. One of the design principles of Ruby is it's readability, and I find
for i in a
...
end
much more readable (and easier to type) than
a.each do |i|
...
end
Why is it not preferred? Do others not also find it more readable? Is it for consistency reasons, e.g., relation with other functions like each_with_index
and variable scoping?
Best How To :
For me, it's uniform syntax. When I am going to do something with array a
, I just start typing a.
. What am I going to do? Filter? a.select
; determine the size? a.size
. Iterate? a.each
etc.
Iterating an array is nothing special and requires no special language construct. Also each
without an immediate block results in an Enumerator, which can be chained with other methods.
Then again, Ruby does have a fine for i in a
loop. So if you are more comfortable with a for loop: by all means, use a for loop.