Search code examples
rubyloopsiteratorenumerator

escaping the .each { } iteration early in Ruby


code:

 c = 0  
 items.each { |i|  
   puts i.to_s    
   # if c > 9 escape the each iteration early - and do not repeat  
   c++  
 }  

I want to grab the first 10 items then leave the "each" loop.

What do I replace the commented line with? is there a better approach? something more Ruby idiomatic?


Solution

  • While the break solution works, I think a more functional approach really suits this problem. You want to take the first 10 elements and print them so try

    items.take(10).each { |i| puts i.to_s }