Forum: Ruby iterator/array question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Susan Sash (Guest)
on 2006-05-15 21:44
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!
Daniel H. (Guest)
on 2006-05-15 21:58
(Received via mailing list)
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}


-- Daniel
Robert K. (Guest)
on 2006-05-15 22:04
(Received via mailing list)
2006/5/15, Daniel H. <removed_email_address@domain.invalid>:
>       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}

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

robert
This topic is locked and can not be replied to.