Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 访问散列/数组中的数据_Ruby_Ruby On Rails 3 - Fatal编程技术网

Ruby 访问散列/数组中的数据

Ruby 访问散列/数组中的数据,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,您好,我有以下对象(为了示例简化) 我希望特别访问“订单计数”。如何在rails应用程序中执行此操作 我试过note\u attributes.name和note\u attributes[name]但是我没有任何运气 object[:note\u attributes][0][:name] 因评论而更新: object.note\u attributes[0]。name您应该能够执行note\u attributes[0]。name要访问它,您有一个数组,其中有一个散列。因此,您需要访问数组的

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

我希望特别访问
“订单计数”
。如何在rails应用程序中执行此操作


我试过
note\u attributes.name
note\u attributes[name]
但是我没有任何运气

object[:note\u attributes][0][:name]

因评论而更新:


object.note\u attributes[0]。name

您应该能够执行
note\u attributes[0]。name
要访问它,您有一个数组,其中有一个散列。因此,您需要访问数组的第一个元素以获得如下哈希值:
note\u attributes[0]
note\u attributes.first

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

Ruby哈希过去看起来像:
{:name=>“Order\u Count”}
,但现在可以使用冒号而不是箭头。当您使用一个符号作为键时,Ruby使它看起来特别漂亮,并允许您这样做:
{name:“Order\u Count”}
(这就是您所做的)

因此,要从数组中的散列中获取键为
:name
的属性,可以执行以下操作:

note_attributes[0][:name]


我把你的变量名改为“object”,但它应该是其他的。变量名没有显示在你的代码中。是的,我发现了,并替换了它,但它仍然不起作用。它为#(这是我的对象)提供了未定义的方法“[]”,您可以尝试
对象。注意_属性[0]。名称
?另外,我建议您将类名
shopifigapi::Order
放在问题中。您正在使用
shopify\u api
gem吗?如果是这样的话,将其添加为标记。这似乎是散列中的一个键值对,而散列不是对象(我想这是向下投票的原因)。您需要通过将其括在大括号中使其成为散列。(如果你不这样做,无论是否合理,都会有更多的反对票)。当你这样做的时候,我建议你把它分配给一个变量(例如,
h={note_attributes..}
),这样读者可以在答案和评论中引用这个变量。
note_attributes[0][:name]
note_attributes.first[:name]