简体   繁体   中英

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

I'm new to Ruby and still learning about hashes. 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 ):

    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

Two questions:

1) How do I return the 'labels', 'titles', and 'names' from array 'a: [ ]' only?

2) How do I add and save a new hash under array 'a: [ ]' but not ':b [ ]'?

Thanks in advance for the help!

You can return values for specific key (: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

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 do |k, a|
  a.each do |h|
    puts h[:name]
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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