如何解析这个键值对?
这是执行 puts get_account_entry.inspect
的输出
[[{:value=>"8b08e26a-6d35-7140-9e41-4c5b4612c146", :name=>"id"}, {:value=>"Typhoon Corporation", :name=>"name"}]]
我如何提取 :name =>; 的值例如“id”?最初我认为它就像一个散列,所以 get_account_entry[id] 会产生结果,但仔细检查后却发现它没有意义。
但那么我如何获得这些值呢?
Chuck 让我走上了正确的道路,但仍然需要帮助:
puts get_account_entry[0].map {|hash| [hash[:name], hash[:value]] }
这是 ruby 控制台中的输出:
> id
> 8b08e26a-6d35-7140-9e41-4c5b4612c146
> name
> Typhoon Corporation
This is the output from doing puts get_account_entry.inspect
[[{:value=>"8b08e26a-6d35-7140-9e41-4c5b4612c146", :name=>"id"}, {:value=>"Typhoon Corporation", :name=>"name"}]]
How do I extract out the value of :name => "id" for example? Originally I thought it was like a hash, so get_account_entry[id] would produce the result, but it doesn't which makes sense on closer inspection.
But then how do I get at the values?
Chuck got me on the right path, but still need help:
puts get_account_entry[0].map {|hash| [hash[:name], hash[:value]] }
This is the output in the ruby console:
> id
> 8b08e26a-6d35-7140-9e41-4c5b4612c146
> name
> Typhoon Corporation
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你已经接近正确的了。它是一个包含哈希数组的数组,它们一起形成一种类似哈希的结构。要获取具有相应名称“id”的值,您必须执行 get_entries[0].find {|field|字段[:名称] == 'id'}[:值]。最初的
[0]
让我们进入无意义的外部数组,然后我们需要找到哪个哈希具有:name
条目“id”,然后我们向它询问其:value
条目的值。如果您想将此名称-值数据结构转换为普通哈希,您可以执行
Hash[get_entries[0].map {|hash| [哈希[:名称], 哈希[:值]] }]
。You're close to right. It's an array containing an array of Hash, which together form a sort of Hash-like structure. To get the value with the corresponding name "id", you'd have to do
get_entries[0].find {|field| field[:name] == 'id'}[:value]
. The initial[0]
gets us inside the pointless outer array, and then we need to find which hash has the:name
entry "id", then we ask it for the value of its:value
entry.If you want to convert this name-value data structure into a normal hash, you could do
Hash[get_entries[0].map {|hash| [hash[:name], hash[:value]] }]
.最外面的方括号“[]”表示这个序列化代表一个数组。
您是否尝试过类似 get_entries[0][id] (或 get_entries[0][0][id] 因为它是双括号)?
The most external square brackets "[]" says that this serialization represents an array.
Have you tried something like get_entries[0][id] (or get_entries[0][0][id] since it's a double bracket)?
这就是我的做法。
希望这有帮助。
This is how I would approach.
Hope this helps.