From: ara.t.howard@... Date: 2007-01-20T05:59:34+09:00 Subject: Re: local variable assertion On Sat, 20 Jan 2007 dflanagan@gmail.com wrote: > > I disagree. Local variables are used most often. I see a good chance of > getting bitten by this problem, especially when using generic variable names > like i or x as block parameters to loop iterators. > i've been writing ruby in production 90% of my coding time for nearly 6 years and have hit this only one or two times. i'd say it's a valid concern but nearly always a massive sign of code smell: one simply should never have too many variables to keep in ones head in scope at any given moment. if one does, it's time to refactor. > Suppose you've got a simple loop to iterate through an array > > data.each { |x| x*x} > > Now you refactor some code and end up cutting-and-pasting that loop into a > method that happens to use x as a parameter. Suddenly your loop behaves > differently. x is no longer local to the block and it overwrites the local > variable in your method. you're quite right. what i fail to see is how a 'local' method changes that one bit. consider, say you paste the above snippet into some code that has an 'x' defined 20 lines up, you don't notice and introduce a bug. in order to prevent this you are advocating this local :x do data.each { |x| x*x} end so a re-def of x will raise an error. at first glance that seems ok. consider this however: one must __know_in_advance__ which vars to declare local and which not. in your example it's the only obivous one but, in fact, there are two candidates: 'x' and 'data'. now, in this case we know that we do, in fact, require the 'data' var __not__ to be local, but to picked up from the current scope. note that it's __precisely__ this ability to do mixed scoping which makes blocks useful at all - otherwise we'd all just pass stuff around. perhaps you see where i'm going? in order to use local effectively with even a moderately complex peice of code one needs to look at the code and decide which vars should be local, which should be block-local (ruby 1.9), and which should be scoped normally. all this has to be known __up_front__! the thing is, if i have to know, as a programmer, up front which vars to declare local then i don't have a problem any more! ;-) so, imho, you are correct in pointing out a source for errors but blocks, like all coding contructs, must be weighed by comparing advantages vs. disadvatages and the mixing of scopes certainly resides on both lists. it would be nice if way existed to solve the problem you have underscored, but if that solution requires me to do the same amount of work that i had to do before to solve it 'manually' then it simply becomes line noise and, as we all know, any code you write that you don't have to is simply adding bugs. my 2cts. kind regards. -a -- we can deny everything, except that we have the possibility of being better. simply reflect on that. - the dalai lama