icecreamsoda
icecreamsoda

Reputation: 3

access elements in Ruby nested hash

I am trying to access the elements in a nested hash where keys are similar symbols.

favs = { 
  :art => "painters",
  :survey1 => [ 
    {:name => "Josh", :painter => "Dali" },
    {:name => "Mona", :painter => "Monet"}
  ],
  :survey2 => [ 
    {:name => "Leon", :answer => "None"},
    {:name => "Port", :answer => "Picasso"},
  ]
}

Q1: Delete Leon-

I came up with this:

favs[:survey2].each { |hash|
hash.delete_if { |k,v| 
v=="Leon"
}
}

but I couldn't figure out how to tie the second key value pair in (the answer/painter) after removing just the name.

Q2 Return Josh's favorite painter - same problem, I can find :name=>Josh but not sure how to return corresponding painter.

Thanks in advance

Upvotes: 0

Views: 1120

Answers (2)

utdemir
utdemir

Reputation: 27216

A1:

You must delete Hash's in Array, not elements in Hash.

favs[:survey2].delete_if {|i| i[:name] == "Leon"}

A2:

favs[:survey1].find { |i| i[:name] == "Josh" }[:painter]

Upvotes: 1

ian
ian

Reputation: 12251

Like I mention in the comments, don't use primitive when they become too, erm, primitive. Nested anythings are a hint you're at that stage:

class Student
  attr_reader :name
  attr_reader :favourite_painter

  def initialize( name, opts={} )
    @name = name
    @favourite_painter = opts[:favourite_painter]
  end
end

students = []
students << Student.new( "Josh", :favourite_painter => "Dali" )
students << Student.new( "Mona", :favourite_painter => "Monet" )
# etc…

And see http://www.ruby-doc.org/core-2.0/Array.html and http://www.ruby-doc.org/core-2.0/Enumerable.html.

Upvotes: 1

Related Questions