From: raja@... (Raja S.) Date: 2001-03-16T22:10:02+09:00 Subject: [ruby-talk:12740] Re: FEATURE REQUEST: 'my' local variables matz@zetabits.com (Yukihiro Matsumoto) writes: >Hi, >In message "[ruby-talk:12718] Re: FEATURE REQUEST: 'my' local variables" > on 01/03/16, "Doug Edmunds" writes: >|code snippet1: >| >|animal = %w( cat dog cow duck ) >|vegetable = %w( tomato carrot onion ) >|vegetable.each { |animal| puts animal } >|p 'now animal is: ', animal # result is 'onion'!!! >I think the problem is you were assigning vegetables to the variable >named "animal". I think you don't complain > int i; > i = 22; > for (i=0; i<10; i++) { > printf("i=%d\n", i); > } > printf("i=%d\n", i); /* result is 9!! */ Yes, but that is C. This is Ruby --- life is supposed to be better in this world :-). I would love procs/lambdas of Ruby to function like those of Lisp --- lambda parameters are local. If you want to access a non-local variable then don't shadow. Scheme/Lisp gave (and continue to give) me a lot of joy. Ruby rivals that and in some cases exceeds in the sheer pleasure one gets with working with it. But sadly this one aspect has caused me grief occasionally and when it does it is not so easy to detect. Capturing a non-local variable via a proc parameter is done purely for efficiency reasons, right? But sadly, while the program's efficiency may increase my efficiency gets impaired :-). The potential violation of the "principle of locality" (changes in one part of a program should minimize its effect on other parts) seems to me to be too much of a price to just for a slight efficiency boost. Inadvertent shadowing is much easier to detect and deal with (a local problem) than inadvertent variable capture (a global problem). I've now come to the stage where I'm preferring to label all my block parameters with an explicit under_score prefix just to avoid advertent variable capture; proc {|_a, _b| ...} but that still doesn't solve the problem when my code is shared with someone else who happens to use _ prefixes for non-local variables too. This would really be nice if it could be changed. But is it too late? Is flagging a warning the best that can be done now? Wonder how many people really do use the modifications to a block parameter outside the block. With block local parameters, one could still get that effect by avoiding shadowing and explicitly accessing the non-local. Regards, Raja