escaping the .each { } iteration early in Ruby

BuddyJoe picture BuddyJoe · Oct 14, 2009 · Viewed 59k times · Source

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?

Answer

nimrodm picture nimrodm · Oct 14, 2009

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 }