SupremeA
SupremeA

Reputation: 1621

Remove an item from each hash in an Array of hashes

I have an array of hashes like this:

array = [{
  "id"=>"ABC",
  "account"=>"XYZ", 
  "date"=>"2014-07-21",
  "amount"=>200,  
  "score"=>{"location"=>{"city"=>1, "state"=>1}, "name"=>1},
  "cat"=>#<Tipper::Category:0xb666fb0
    @type={"primary"=>"special"},
    @hierarchy=["Transfer","Withdrawal", "ATM"],
    @id="21012002"
  >,  
  "state"=>"CA"
},
{"id=>"XYZ","account"=>"987"}]

I want to iterate through each hash in the array and remove the "category" piece from each hash and produce an array of hashes without the "category" item in any of the hashes. I tried this:

filtered_array = array.reject { |t| array.include? t['cat'] }

This is not doing it.

Upvotes: 0

Views: 344

Answers (2)

Zoran
Zoran

Reputation: 4226

Assuming you have an array of hashes:

array = [ {"id" => 1, "name" => "bob", "cat" => "dog"}, 
          {"id" => 2, "name" => "jim", "cat" => "mouse"}, 
          {"id" => 1, "name" => "nick", "cat" => "fish"} ]

You can do something like the following:

array.map { |hash| hash.reject {|k, v| k == "cat" } }

This returns a new array of hashes with the cat pairs removed, while still preserving the original array:

=> [{:id=>1, :name=>"bob"}, {:id=>2, :name=>"jim"}, {:id=>1, :name=>"nick"}]

Hope it helps!

Upvotes: 1

Nafaa Boutefer
Nafaa Boutefer

Reputation: 2359

You can use map and delete

this will work the actual instances of the hashes, so the array will be modified.

array.each{ |hash| hash.delete('cat') }

you can do this to get a new array and keep the first one non touched.

new_array = array.map do |hash| 
   new_hash = hash.dup
   new_hash.delete('cat')
   new_hash
}

Upvotes: 1

Related Questions