访问散列/数组中的数据

Accessing Data inside hash / array

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

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

我想专门访问 "Order_Count"。如何在我的 rails 应用程序中执行此操作?

我已经尝试了 note_attributes.namenote_attributes[name] 但我没有任何运气。

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

因评论而更新:

object.note_attributes[0].name

您应该可以note_attributes[0].name访问它

你有一个数组,里面只有一个散列。所以你需要访问数组的第一个元素来获取你的散列,如下所示:note_attributes[0]note_attributes.first.

然后您可以访问散列中的元素。在这种情况下,您的键是符号,如下所示::name

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

因此,要从数组的散列中获取具有键 :name 的属性,您可以这样做:

note_attributes[0][:name]

note_attributes.first[:name]