Automatic counter in Ruby for each?

As people have said, you can use

each_with_index

but if you want indices with an iterator different to "each" (for example, if you want to map with an index or something like that) you can concatenate enumerators with the each_with_index method, or simply use with_index:

blahs.each_with_index.map { |blah, index| something(blah, index)}

blahs.map.with_index { |blah, index| something(blah, index) }

This is something you can do from ruby 1.8.7 and 1.9.


[:a, :b, :c].each_with_index do |item, i|
  puts "index: #{i}, item: #{item}"
end

You can't do this with for. I usually like the more declarative call to each personally anyway. Partly because its easy to transition to other forms when you hits the limit of the for syntax.


Yes, it's collection.each to do loops, and then each_with_index to get the index.

You probably ought to read a Ruby book because this is fundamental Ruby and if you don't know it, you're going to be in big trouble (try: http://poignantguide.net/ruby/).

Taken from the Ruby source code:

 hash = Hash.new
 %w(cat dog wombat).each_with_index {|item, index|
   hash[item] = index
 }
 hash   #=> {"cat"=>0, "wombat"=>2, "dog"=>1}

Tags:

Ruby

Syntax