0

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!

Chris
  • 51
  • 6
  • You might want to check out the `neo4j` / `neo4j-core` gems which let you work with Neo4j at a higher level. I'm one of the maintainers and I'm happy to help if you have any questions! – Brian Underwood Jun 10 '15 at 12:22
  • @BrianUnderwood Cool, I looked at it today and it looks like some great stuff! And thanks for the offer, I actually have one [question that's somewhat related.](http://stackoverflow.com/questions/30770914/how-do-i-create-a-neo4j-relationship-via-the-rails-console) – Chris Jun 11 '15 at 03:15
  • Awesome, looks like my colleague Chris beat me to it! ;) I added a bit, though – Brian Underwood Jun 11 '15 at 17:04

1 Answers1

0

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
Lukas Baliak
  • 2,849
  • 2
  • 23
  • 26