# Accessing the count/iteration # within an "each"?

**URL:** <https://www.ruby-forum.com/t/accessing-the-count-iteration-within-an-each/106974>\
**Category:** Ruby\
**Created:** [June 15, 2007, 11:36pm UTC](https://www.ruby-forum.com/t/accessing-the-count-iteration-within-an-each/106974 "2007-06-15T23:36:15Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![greg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/71c47a/32.png) [@greg](https://www.ruby-forum.com/u/greg)\
**Post date:** [June 15, 2007, 11:36pm UTC](https://www.ruby-forum.com/t/accessing-the-count-iteration-within-an-each/106974/1 "2007-06-15T23:36:15Z")

</div>

Hi,

Is there a way to access the count / iteration# within an “each” loop?  
i.e.  
how many times through the loop one is?

testhash.each { |d|  
puts

}

Tks  
Greg

---

<div class="post-metadata">

**Author:** ![greg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/71c47a/32.png) [@greg](https://www.ruby-forum.com/u/greg)\
**Post date:** [June 15, 2007, 11:39pm UTC](https://www.ruby-forum.com/t/accessing-the-count-iteration-within-an-each/106974/2 "2007-06-15T23:39:15Z")

</div>

> how many times through the loop one is?
> 
> testhash.each { |d|  
> puts
> 
> }

testhash.each\_with\_index {|d, i| puts i}

- donald

---

<div class="post-metadata">

**Author:** ![greg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/71c47a/32.png) [@greg](https://www.ruby-forum.com/u/greg)\
**Post date:** [June 15, 2007, 11:41pm UTC](https://www.ruby-forum.com/t/accessing-the-count-iteration-within-an-each/106974/3 "2007-06-15T23:41:15Z")

</div>

Greg H. wrote:

> Is there a way to access the count / iteration# within an “each”  
> loop? i.e.  
> how many times through the loop one is?  
> ruby$ ri Enumerable#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}
```

---

<div class="post-metadata">

**Author:** ![greg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/71c47a/32.png) [@greg](https://www.ruby-forum.com/u/greg)\
**Post date:** [June 16, 2007, 3:26am UTC](https://www.ruby-forum.com/t/accessing-the-count-iteration-within-an-each/106974/4 "2007-06-16T03:26:36Z")

</div>

excellent - thanks guys
