简体   繁体   English

Ruby在哈希内的数组内访问哈希(并添加新哈希)

[英]Ruby access hash within an array within a hash (and add new hash)

I'm new to Ruby and still learning about hashes. 我是Ruby的新手,仍然在学习哈希。 I've tried looking here for other similar answers but wasn't able to find anything that completely answered my question. 我试图在这里寻找其他类似的答案,但找不到任何能够完全回答我的问题的东西。

I have some data stored in a hash structure that I'm feeding into a script that updates a Neo4j database ( so this data structure is important ): 我将一些数据存储在散列结构中,然后将其输入到更新Neo4j数据库的脚本中( 因此此数据结构很重要 ):

    data = {
        a: [
        {
            label: 'Person',
            title: 'Manager',
            name: 'Mike Waldo'
        },
        {   
            label: 'Person',
            title: 'Developer',
            name: 'Jeff Smith',
        },
        ],

        b: [
        {   
            type: 'ABC',
            source: 'abcde',
            destination: ['Jeff Dudley', 'Mike Wells', 'Vanessa Jones']
        }
        ]
    }

I've figured out how to return individual values: 我想出了如何返回单个值:

data.each{|x, y| puts y[0][:name]}

Returns: Mike Waldo 返回:Mike Waldo

Two questions: 两个问题:

1) How do I return the 'labels', 'titles', and 'names' from array 'a: [ ]' only? 1)如何仅从数组“ a:[]”返回“标签”,“标题”和“名称”?

2) How do I add and save a new hash under array 'a: [ ]' but not ':b [ ]'? 2)如何在数组'a:[]'下而不在':b []'下添加和保存新的哈希?

Thanks in advance for the help! 先谢谢您的帮助!

You can return values for specific key (:a) 您可以返回特定键的值(:a)

data[:a]
# => [{:label=>"Person", :title=>"Manager", :name=>"Mike Waldo"}, {:label=>"Person", :title=>"Developer", :name=>"Jeff Smith"}]

And if you need to save value to :a Hash so you just use 而且,如果您需要将值保存到:a哈希中,则只需使用

data[:a] << {:label => "new label", :name => "new name", :titles => "new title"}
# => [{:label=>"Person", :title=>"Manager", :name=>"Mike Waldo"}, {:label=>"Person", :title=>"Developer", :name=>"Jeff Smith"}, {:label=>"new label", :name=>"new name", :titles=>"new title"}]

btw: your command (data.each{|x, y| puts y[0][:name]}) just return name value for fist hash if you need all names for all hashe you can use 顺便说一句:您的命令(data.each {| x,y |放入y [0] [:name]})仅在需要哈希的所有名称时才返回拳头哈希的名称值

data.each do |k, a|
  a.each do |h|
    puts h[:name]
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM