escaping the .each { } iteration early in Ruby
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 }
There is no ++
operator in Ruby. It's also convention to use do
and end
for multi-line blocks. Modifying your solution yields:
c = 0 items.each do |i| puts i.to_s break if c > 9 c += 1 end
Or also:
items.each_with_index do |i, c| puts i.to_s break if c > 9end
See each_with_index
and also Programming Ruby Break, Redo, and Next.
Update: Chuck's answer with ranges is more Ruby-like, and nimrodm's answer using take
is even better.
break
works for escaping early from a loop, but it's more idiomatic just to do items[0..9].each {|i| puts i}
. (And if all you're doing is literally printing the items with no changes at all, you can just do puts items[0..9]
.)