In Ruby:
for i in A do # some code end
is the same as:
A.each do |i| # some code end
for is not a kernel method:
- What exactly is ‘
for‘ in ruby - Is there a way to use other keywords to do similar things?
Something like:
total = sum i in I {x[i]}
mapping to:
total = I.sum {|i] x[i]}
It’s almost syntax sugar. One difference is that, while
forwould use the scope of the code around it,eachcreates a separate scope within its block. Compare the following:versus