How to access index of my collection object?

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?.

On Aug 22, 7:35 am, Rails L. [email protected]
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

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

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs