From: David Alan Black Date: 2001-05-03T08:43:33+09:00 Subject: [ruby-talk:14559] Re: Arggg Bitten by the block var scope feature!!! On Thu, 3 May 2001, Wayne Scott wrote: > > I just spend a day debugging a elegant script that had this > function. > > #simplified for this discussion > def fetch(arg2) > # cheesy block to flush cache if it has gotten too big > if @cache.length > 200 > # one pass at flushing cache > @cache.dup.each do |arg2, file| ## (1) > file.flush > @cache.delete arg2 > end > end > unless @cache[arg2] ## (2) > @cache[arg2] = @cl.new(@arg1, arg2) > end > @cache[arg2] > end > > The bug is that at (1) the variable 'arg2' is not local to the block > like I was expecting, but was just a copy of the function parameter > 'arg2'. So when I hit the normal part of the function at (2) the > parameter is trashed if I happened to have executed (1). Wouldn't it be easier and clearer, and less dangerous (in any language), not to reuse the parameter variable name for a temporary variable inside the method? I'm not sure why you'd want to call that block variable arg2, except specifically to take advantage of the powerful feature of Ruby that interprets that to mean you want to use the same variable :-) |arg2, file| at the beginning of your block basically means: each time through the block, do this: arg2 = file = So you really don't want Ruby to assume that you mean some new arg2, any more than you would if you did: def thing(arg2) [1,2,3].each do |n| arg2 += n end end David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav