smilin_stan smilin_stan - 6 months ago 14
Ruby Question

Initialising a hash of hashes

Let's say I have a hash of hashes as follows:

order_history = {}

order_history[customer_id][order_id] = { :total_spend => order_spend, :date => order_date }


When I add entries into this hash I have to check whether the customer_id exists first, like so:

order_history[customer_id] = {} unless order_history.has_key?(customer_id)


Then, I can add the details for an individual order:

order_history[123][456] = { :total_spend => 200.45, :date => 2016-05-03 }


Is it possible to declare the order_history hash as a hash-of-hashes at the outset, so I don't have to do the test every time? Or is there a way of telling ruby that when a new key is created, set the value to be a new, empty hash?

Answer

You can try this for your hash :

h = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }

h['bar'] -> {}
h['tar']['star']['par'] -> {}

For more information, this answer is from this post