0

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.

3
  • Whatever you have is invalid. Commented Jun 6, 2015 at 1:13
  • What is your question? Commented Jun 6, 2015 at 1:13
  • The data is called array, but the code snippet never references array Commented Jun 6, 2015 at 9:36

2 Answers 2

1

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 } 
Sign up to request clarification or add additional context in comments.

Comments

1

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!

3 Comments

You have to return the hash in the map block, because delete will return the value of the deleted key. So your solution will return an array of the categories.
And you should note that the hashes in the array will all be modified, so the subject array and the resulting array are identical, and contains the same instances. Which is not what I would suggest.
Thanks for your feedback! I have actually just modified my code to use reject. This returns the desired array of hashes, while still preserving the original array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.