Ruby for-loops are surprising

From @JEG2’s interesting blog post

Ruby 1.8 has block arguments reusing in scope variables of the same name, and those variable s can change as a side effect of the block’s execution. Ruby 1.9 does not have this behavior.

Ruby for-loops are actually equivalent to using .each on the index and a block for the loop body. The index variable is created prior to entering the block body if it doesn’t already exist in scope. You can see now that in 1.8, this might lead to some interesting results. Writing the loop with .each and a block gives a different behavior than the for-loop.

Finally, if the for-loop index is used in, say, a closure in the for-loop body, well, surprising things ensue when the loop index is set to the new value instead of establishing a new binding on each loop iteration (ruby has the same behavior as python, javascript, and Lisp. Haskell does it differently). Go read @JEG2’s post for the full skinny, but I’ll leave you with this:

results = [ ]for i in 1..3  results << lambda { i }endputs results.map { |l| l.call }# >> 3# >> 3# >> 3

 

Advertisements
Previous Post
Next Post
Leave a comment

1 Comment

  1. Fred Nixon

     /  June 14, 2011

    Don’t laugh about the FB like. I’m just testing posterous. OK, laugh if you wish.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: