Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a specific element from a nested hash

Tags:

I am trying to work with a nested hash. I have a deck of cards represented as follows:

deck_of_cards = { :hearts => {:two => 2, :three => 3, :four => 4, :five => 5, :six => 6, :seven => 7, :eight => 8, :nine => 9, :ten => 10, :jack => 10,              :queen => 10, :king => 10, :ace => 11}, :spades => {:two => 2, :three => 3, :four => 4, :five => 5, :six => 6, :seven => 7, :eight => 8, :nine => 9, :ten => 10, :jack => 10,              :queen => 10, :king => 10, :ace => 11}, :clubs => {:two => 2, :three => 3, :four => 4, :five => 5, :six => 6, :seven => 7, :eight => 8, :nine => 9, :ten => 10, :jack => 10,              :queen => 10, :king => 10, :ace => 11}, :diamonds => {:two => 2, :three => 3, :four => 4, :five => 5, :six => 6, :seven => 7, :eight => 8, :nine => 9, :ten => 10, :jack => 10,              :queen => 10, :king => 10, :ace => 11} } 

My goal is to be able to remove one specific card from the deck and return the deck of cards without that specific card. Would anyone be able to help me on how to iterate through the hash and remove a card like the two of clubs?

deck_of_cards[:two][:clubs] 

This code works to remove a suit of cards, but I cant figure out how to remove a specific card

deck_of_cards.delete_if {|k, v| k == :spades} 
like image 671
BC00 Avatar asked Jun 20 '12 17:06

BC00


People also ask

How do you remove an item from a hash?

We can use the delete(key) method to delete an entry of a hash. It returns the associated value of the entry deleted.

What is a nested hash?

Nested hashes allow us to further group, or associate, the data we are working with. They help us to deal with situations in which a category or piece of data is associated not just to one discrete value, but to a collection of values.


2 Answers

Just do this:

deck_of_cards[:clubs].delete(:two) 
like image 64
SwiftMango Avatar answered Oct 05 '22 02:10

SwiftMango


You can remove an element and return the original hash also using tap function like this

deck_of_cards.tap{|d|    d[:hearts].tap{|h|      h.delete(:two)   } } 

this will return the deck_if_cards hash without :two key

you can do it in one line also

    deck_of_cards.tap{|d| d[:hearts].tap{|h| h.delete("two")}} 
like image 28
Moustafa Samir Avatar answered Oct 05 '22 00:10

Moustafa Samir