(Sorry for the newbie question.) In Ruby, what is the difference between the loops:
@cars.each do |car|
and
for car in @cars do
?
is there a difference in efficiency, or why do we need two (or more) ways to express the same thing? The second way seems more elegant/natural to me, but I may be missing some crucial observation, why the first may be the better choice.
More people use the
@cars.eachnotation because that generalizes to other methods (like#inject,#each_with_index,#map, etc, as well as non-iterator callbacks).for/in is mainly just syntactic sugar for
#each. The main difference in how the two work is in variable scoping:for/in leaves the iterator variable in scope afterwards, while
#eachdoesn’t.Personally, I never use ruby’s for/in syntax.