Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index count method for iterators in ruby?

Tags:

ruby

When moving over an iteration such as:

array.each do |row|
  puts "Current row count: " + row.current_row_index
  # do some more stuff
end

Is there a way to get the index of the current iteration / row? Obviously I can just throw in a counter, but I'm curious if there's a shortcut for an index function that shows it's current position.

Been digging through the available methods via pry, however I've not seen anything that seems to do this out of the box.

like image 642
ylluminate Avatar asked Feb 21 '12 19:02

ylluminate


2 Answers

array.each_with_index |row, index|
  puts index
end
like image 125
David Grayson Avatar answered Oct 04 '22 02:10

David Grayson


If you need exactly the index

array.each_index do |index|
  puts index
end
like image 43
megas Avatar answered Oct 04 '22 00:10

megas