MrPizzaFace
MrPizzaFace

Reputation: 8086

Removing a hash from an array of hashes?

h = {
    :vehicle => [
        [0] {
            :make => "Honda",
            :year => 2010
        },
        [1] {
            :make => "Kia",
            :year => 2014
        },
        [2] {
            :make => "Saturn",
            :year => 2005
        }
    ]
}

I would like to remove {:make=>"Kia", :year=>2014} so that h is:

h = {
    :vehicle => [
        [0] {
            :make => "Honda",
            :year => 2010
        },
        [1] {
            :make => "Saturn",
            :year => 2005
        }
    ]
}

I tried:

h[:vehicle].delete_if{ |_,v| v == "Kia" } 
 #=> does nothing

h.delete_if{ |_,v| v == "Kia" } 
 #=> does nothing

h[:vehicle].tap { |_,v| v.delete("Kia") } 
 #=> does nothing

h.delete("Kia") 
 #=> nil

h[:vehicle].delete("Kia") 
 #=> nil

Here's where I'm getting a headache:

h[:vehicle].include?("Kia") 
 #=> false 

h[:vehicle][1] 
 #=> {:make=>"Kia", :year=>2014} 

h[:vehicle][1].include?("Kia") 
 #=> false

Thanks for the help.

Upvotes: 0

Views: 153

Answers (1)

Alex.Bullard
Alex.Bullard

Reputation: 5563

h[:vehicle].delete_if { |h| h[:make] == 'Kia' }

Will return a copy of h with Kia removed. Note that although its a somewhat strange way to do it, your first example does work for me. Remember that you have to look at the returned value to see the result - delete_if does not modify the original hash.

Upvotes: 1

Related Questions