Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Each with index up to a certain number ruby on rails

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?

like image 857
Simon Kiely Avatar asked Dec 06 '22 18:12

Simon Kiely


2 Answers

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
like image 110
Aleksei Matiushkin Avatar answered Jan 05 '23 01:01

Aleksei Matiushkin


Another solution is to use Enumerable#first

array.first(10).each_with_index do |row, index|
  puts index
end
like image 43
mrazicz Avatar answered Jan 05 '23 00:01

mrazicz