【问题标题】:Iterating through attributes with index in ruby在ruby中使用索引遍历属性
【发布时间】:2016-01-27 22:46:38
【问题描述】:

如何在 ruby​​ 中为属性的迭代添加索引?

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

我已经尝试过使用 each_with 索引:

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

但是索引会放在哪里呢?

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

你可以这样做

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

更多详情possible-to-access-the-index-in-a-hash-each-loop

【讨论】:

    【解决方案2】:

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

    Toys 必须是成员对象(属性不适用于集合)。

    -

    我也测试了只声明“key”,如下:

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

    attr 在此实例中作为 数组 返回,其中键/值分别用作数组的 01 元素。

    【讨论】:

      猜你喜欢
      • 2016-09-25
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多