smilin_stan smilin_stan - 1 year ago 57
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 Source

You can try this for your hash :

h = { |h, k| h[k] = }

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

For more information, this answer is from this post