Each with an index of up to a certain number of rubies on rails

Stupid question, which I think, but I searched high and low for a definitive answer to this and found nothing.

array.each_with_index |row, index|
  puts index
end

Now, let's say I only want to print the first ten elements of the array.

array.each_with_index |row, index|
  if (index>9)
     break;
  end
   puts index
end

Is there a better way than this?

+4
source share
2 answers

Use Enumerable#take:

array.take(10).each_with_index |row, index|
   puts index
end

If the condition is more complex, use take_while.

Rule of thumb: Iterators can be bound:

array.take(10)
     .each
   # .with_object might be chained here or there too!
     .with_index |row, index|
   puts index
end
+13
source

Another solution is to use Enumerated # first

array.first(10).each_with_index do |row, index|
  puts index
end
+3
source

All Articles