[英]Iterating through attributes with index in ruby
如何在ruby中为属性的迭代添加索引?
<% @child.toys.attributes.each do |attr_name, attr_value| %>
我已经尝试过each_with索引:
<% @child.toys.attributes.each_with_index do |attr_name, attr_value| %>
但是索引会进入哪里?
你可以这样做
<% @child.toys.attributes.each_with_index do |(attr_name, attr_value), idx| %>
有关更多详细信息, 可以在每个循环中访问索引
.each_with_index
附加index
变量:
%w(cat dog wombat).each_with_index {|item, index|
hash[item] = index
}
hash #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
在您的示例中:
<% @child.toys.attributes.each_with_index do |key,value,index| %>
<%= key %>
<%= value %>
<%= index %>
<% end %>
玩具需要成为成员对象(属性对集合不起作用)。
-
我还通过仅声明“密钥”进行了测试,如下所示:
<% @child.toys.attributes.each_with_index do |attr,index| %>
<%= attr[0] %>
<%= attr[1] %>
<%= index %>
<% end %>
在这种情况下, attr
作为数组返回,其中键/值分别用作数组的0
和1
元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.