[英]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.