DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Alexey has posted 28 posts at DZone. View Full User Profile

Ruby: For Vs .each

12.18.2010
| 3117 views |
  • submit to reddit
        Why "for" is syntactic sugar for each method, one should remember sagnificant difference. For declares variables in outer scope (method), while each block declares them in inner.

   for x1 in [1,2]; end
=> [1, 2]
   x1
=> 2
   [1,2].each do |x2|; end
=> [1, 2]
   x2
NameError: undefined local variable or method `x2'
        from (irb):5
        from C:/bin/ruby/bin/irb:12:in `<main>'