Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Ruby for-loops have unusual scoping of loop variables, and if you're not familiar with this it can prove to be a source of bugs. I was bitten by this some years ago when I was first learning Ruby, and it took me a while to track down the problem.

An "each" block has the scoping you'd expect, and is more consistent with the rest of the Ruby looping constructs (like select/filter or collect/map). It's not a huge deal, but there definitely are technical reasons not to use it.



for-loops and .each had weird scoping rules until Ruby 1.9. In Ruby 1.9 for some weird reason they fixed .each but not for-loops. No idea why. So, if you're saying use .each for technical solution to a problem in Ruby, then your proposed solution only works in some versions of Ruby.


The pedantic answer is the code block following the for is not parsed as or represented as a code block internally. You don't need the "do" but Ruby slurps it up to play nice. Only block semantics were fixed, but those for constructs like while, until, for, or loop remain the same as they do not introduce new scope.


How did .each have weird scoping pre-1.9? I've run across problems with for-loops, but .each has always behaved predictably, even in 1.8.

Could you perhaps provide an example of code using .each that does the wrong thing in 1.8, but the right thing in 1.9?


    a = 0
    [1, 2, 3].each { |a| }
    a # => 3


Ah, thanks for the clarification. I guess that means there are at least two odd things about scoping in 1.8 loops.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: