# How to access index of my collection object?

**URL:** <https://www.ruby-forum.com/t/how-to-access-index-of-my-collection-object/174197>\
**Category:** Rails\
**Created:** [August 22, 2009, 8:35am UTC](https://www.ruby-forum.com/t/how-to-access-index-of-my-collection-object/174197 "2009-08-22T08:35:03Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![railslist](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/65b543/32.png) [@railslist](https://www.ruby-forum.com/u/railslist)\
**Post date:** [August 22, 2009, 8:35am UTC](https://www.ruby-forum.com/t/how-to-access-index-of-my-collection-object/174197/1 "2009-08-22T08:35:03Z")

</div>

i have something like

@a = Model.find(:all)

for a in @a  
here i need to know what is my current index / row  
end

how do i get it?.

---

<div class="post-metadata">

**Author:** ![railslist](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/65b543/32.png) [@railslist](https://www.ruby-forum.com/u/railslist)\
**Post date:** [August 22, 2009, 10:27am UTC](https://www.ruby-forum.com/t/how-to-access-index-of-my-collection-object/174197/2 "2009-08-22T10:27:42Z")

</div>

On Aug 22, 7:35 am, Rails L. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> i have something like
> 
> @a = Model.find(:all)
> 
> for a in @a  
> here i need to know what is my current index / row  
> end

I would use each\_with\_index if I were you.

Fred

---

<div class="post-metadata">

**Author:** ![railslist](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/65b543/32.png) [@railslist](https://www.ruby-forum.com/u/railslist)\
**Post date:** [August 24, 2009, 3:57pm UTC](https://www.ruby-forum.com/t/how-to-access-index-of-my-collection-object/174197/3 "2009-08-24T15:57:44Z")

</div>

On Aug 22, 2009, at 3:55 AM, Frederick C. wrote:

> I would use each\_with\_index if I were you.
> 
> Fred
> 
> > ## how do i get it?.

Three suggestions:

1. The index is going to be somewhat arbitrary unless you get the  
records in a well-defined order (i.e., put an :order =\> ‘column\_a,  
column\_b’ option into your find). (Or use a named\_scope or some class  
method on your model rather than letting your controller do the work.)

2. If you want the current index to do something like zebra-striping  
table rows, look at the cycle() helper method for your view.

3. Rather than “for a in @a”, you might want “@a.each do |a|” as James  
Edward G. II explains in “The Evils of the For Loop”  
[http://blog.grayproductions.net/articles/the\_evils\_of\_the\_for\_loop](http://blog.grayproductions.net/articles/the_evils_of_the_for_loop)

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid
