Iterator/array question

Is there a way to iterate through an array, getting the index and the
object at the same time?

For instance, right now I know two ways of going through an array:
array.each do |element|
  print element
end

for i in 0..(array.size - 1) do |i|
  print array[i]
end

Is there a way to mix these two together? As in something like
array.each do |element, i|
  print element.to_s + "is at index " + i.to_s
end

without maintaining a counter through the array?
(Without doing this:
index = 0
array.each do |element|
  print element.to_s + "is at index " + index.to_s
  index += 1
end)

Thanks!

···

--
Posted via http://www.ruby-forum.com/.

$ri each_with_index
--------------------------------------------- Enumerable#each_with_index
      enum.each_with_index {|obj, i| block } -> enum

···

On May 15, 2006, at 7:48 PM, Susan Sash wrote:

Is there a way to iterate through an array, getting the index and the
object at the same time?

------------------------------------------------------------------------
      Calls block with two arguments, the item and its index, for each
      item in enum.

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

-- Daniel

Too bad you disclosed the solution already - I wanted to trade it in
for those turtles...
:wink:

robert

···

2006/5/15, Daniel Harple <dharple@generalconsumption.org>:

On May 15, 2006, at 7:48 PM, Susan Sash wrote:

> Is there a way to iterate through an array, getting the index and the
> object at the same time?

$ri each_with_index
--------------------------------------------- Enumerable#each_with_index
      enum.each_with_index {|obj, i| block } -> enum
------------------------------------------------------------------------
      Calls block with two arguments, the item and its index, for each
      item in enum.

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

--
Have a look: Robert K. | Flickr