from Hacker News

Evils of the For Loop in Ruby

by wolfish on 4/16/09, 5:59 PM with 15 comments

  • by tptacek on 4/16/09, 7:46 PM

    This is interesting, but kind of besides the point. What makes "for" evil in Ruby code is that it's non-idiomatic. A custom block "iterator" covers every case where you might use "for", and more elegantly. In 116,000 lines of Ruby code in our "toolshed" directory, I count zero uses of it; almost none of it is web code, and all our developers are ex-Pythonistas.
  • by mattmcknight on 4/16/09, 7:13 PM

    It doesn't seem evil to me at all, it is exactly what I would expect.

      a = 1
      for a in 1..2
        b = a
      end
      p a
      >> 2
    
    It seems natural that that would change the value of "a", I wouldn't expect a for loop to create a new scoping context. The example with putting a closure into the array is also what I would expect.

    I am not sure what programming language has the scoping rules he expects, but for me there's nothing to see here, moving along...

  • by lysium on 4/17/09, 7:58 AM

    I don't get it. Isn't `|i|` the shorthand version of a lambda binding an i? And `lambda { i }` a lambda not binding anything? So why is the result surprising? I must be missing something.

    Edit: I mean in

      each { |i| p i }
    
    the |i| stands for a shorthand lambda, that binds an i.

    And in

        for i in 1..3
          p i
        end
    
    there is no such binding. So where's the problem? That 'for' should use a lambda?
  • by pkulak on 4/17/09, 5:48 PM

    Isn't that what _all_ languages do with a for loop? Why should Ruby break the mold here?
  • by omouse on 4/16/09, 8:27 PM

    So syntax is to blame once again...