On Wed, Nov 6, 2013 at 1:40 AM, Stefan Salewski <mail / ssalewski.de> wrote:
> On Tue, 2013-11-05 at 16:23 -0800, Justin Collins wrote:
>> This is a block, just like any other block.
>
> Yes indeed -- in Ruby each loop is in first order a block,

Not each loop but #each loop. :-)

$ ruby -e 'for i in 0..5; j=i; puts i; end; puts "--", j'
0
1
2
3
4
5
--
5

There is no block with a for loop.

> that is what
> I forgot. For a block this behaviour is well documented. I have a loop
> with two iterations, in the first iteration I make some expensive
> calculations, which I would like to reuse in the second iteration. So I
> have to define that variables before the loop, and of course I have to
> write j = 0; 2.times{|i| -- not 2.times{|i; j|.
>
> I should really try hard to remember that.

Basically it's the same with most languages with nested scopes:
variables are visible in the smallest surrounding scope. There are
some subtleties in some languages but that rule covers many cases -
certainly for the more popular languages of today.

Depending on what you do #map or #inject might be alternatives (i.e.
if you calculate values per original value or aggregate data in a
single object). There's also #each_with_object.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/