代码之家  ›  专栏  ›  技术社区  ›  chris cozzens

访问哈希/数组内的数据

  •  -2
  • chris cozzens  · 技术社区  · 6 年前

    您好,我有以下对象(为了方便简化示例)

    object = { note_attributes: [{ name: "Order_Count", value: 2 }] }
    

    我希望特别访问 "Order_Count" .如何在rails应用程序中执行此操作?

    我试过了 note_attributes.name note_attributes[name] 但我一点运气都没有。

    3 回复  |  直到 6 年前
        1
  •  1
  •   Alex Dovzhanyn    6 年前

    你应该能够做到 note_attributes[0].name 访问它

        2
  •  1
  •   André Guimarães Sakata    6 年前

    object[:note_attributes][0][:name]

    因评论而更新:

    object.note_attributes[0].name

        3
  •  0
  •   phil    6 年前

    您有一个内部只有一个哈希的数组。因此,您需要访问数组的第一个元素才能获得如下哈希值: note_attributes[0] note_attributes.first

    然后可以访问散列中的元素。在本例中,键是符号,如下所示: :name

    Ruby哈希过去看起来像: { :name => "Order_Count" } ,但现在可以使用冒号代替箭头。当您使用符号作为键时,Ruby使其看起来特别漂亮,并允许您执行以下操作: { name: "Order_Count" } (这就是你所做的)。

    因此,要使用键获取属性 :名称 在数组中的哈希之外,您可以执行以下操作:

    note_attributes[0][:name]
    

    note_attributes.first[:name]