Over a million developers have joined DZone.

Ruby: For Vs .each

·
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 `
'
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}