2

How can i add index to iteration on attributes in ruby?

<% @child.toys.attributes.each do |attr_name, attr_value| %>

I have tried with each_with index:

<% @child.toys.attributes.each_with_index do |attr_name, attr_value| %>

But where would the index go in?

shmnsw
  • 639
  • 2
  • 11
  • 24
  • Have a look at this answer: http://stackoverflow.com/questions/2083570/possible-to-access-the-index-in-a-hash-each-loop – eugen Oct 28 '15 at 08:54

2 Answers2

3

You could do this

<% @child.toys.attributes.each_with_index do |(attr_name, attr_value), idx| %>

For more details possible-to-access-the-index-in-a-hash-each-loop

Community
  • 1
  • 1
akbarbin
  • 4,985
  • 1
  • 28
  • 31
3

.each_with_index appends the index variable:

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

In your example:

<% @child.toys.attributes.each_with_index do |key,value,index| %>
    <%= key %>
    <%= value %>
    <%= index %>
<% end %>

Toys needs to be a member object (attributes won't work on a collection).

-

I also tested with just declaring "key", as follows:

<% @child.toys.attributes.each_with_index do |attr,index| %>
   <%= attr[0] %>
   <%= attr[1] %>
   <%= index %>
<% end %>

attr is returned as an array in this instance, where the key/value is used as 0 and 1 elements of the array respectively.

Richard Peck
  • 76,116
  • 9
  • 93
  • 147