Simon Kiely
Simon Kiely

Reputation: 6050

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?

Upvotes: 4

Views: 1022

Answers (2)

mrazicz
mrazicz

Reputation: 78

Another solution is to use Enumerable#first

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

Upvotes: 2

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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

Upvotes: 13

Related Questions