albatross
albatross

Reputation: 83

Extract correct strings from a MongoDB nested hash in Ruby

I am new to Ruby and need to access a MongoDB database and return some info from a search. So far I can get the required record but I am having difficulty extracting the info from the nested hash that is returned.

hash = {"Skills"  => [{"_id" => 200, "description" => "Running"}, {"_id" => 201, "description" => "Jumping"}]}

This is the hash that is returned. I can access the required hash but cannot seem to extract just the "Running" and "Jumping" strings I require.

I have tried

puts hash["Skills"]

but I just get:

{"_id"=>200, "description"=>"Running"}
{"_id"=>201, "description"=>"Jumping"}

What I need returned is:

"Running"
"Jumping"

I would have thought that the following would have worked:

puts hash["Skills"]["Description"]

Upvotes: 2

Views: 49

Answers (2)

albatross
albatross

Reputation: 83

Figured this out now. I Just realised while doing the washing up that it was of course an array. I will now explore Davids more elegant answer

hash["skills"].each do |h|
    puts h["description"]
end


Running
Jumping

Upvotes: 0

David S.
David S.

Reputation: 730

If you look carefully, the Skills key of your hash is an array and not another hash. Therefore, you could achieve your solution by using Array#map:

hash['Skills'].map { |s| s['description'] }
# => ["Running", "Jumping"]

Upvotes: 1

Related Questions