简体   繁体   中英

Iterating through attributes with index in ruby

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM