Silly question I think, but I've searched high and low for a definitive answer on this and found nothing.
array.each_with_index |row, index|
  puts index
end
Now, say I only want to print the first ten items of the array.
array.each_with_index |row, index|
  if (index>9)
     break;
  end
   puts index
end
Is there a better way than this?
Use Enumerable#take:
array.take(10).each_with_index |row, index|
   puts index
end
If the condition is more complicated, use take_while.
The rule of thumb is: iterators might be chained:
array.take(10)
     .each
   # .with_object might be chained here or there too!
     .with_index |row, index|
   puts index
end
                        Another solution is to use Enumerable#first
array.first(10).each_with_index do |row, index|
  puts index
end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With