Sunday, May 13, 2007

[ruby] Hash of Hashes

One little bit that was not so obvious from the various Ruby docs - How to create Hash that has Hash as values.

This works:
$States = Hash.new()
$States["California"] = Hash.new()
$States["California"].store("Los Angeles", Hash.new())
$States["California"].fetch("Los Angeles").store("District 1", "90035")

This does not work (does not actually give you a syntax error. the child hash assignment would go through silently, but you can never get back the child hash)
$States = Hash.new()
$States["California"] = Hash.new()
$States["California"]["Los Angeles"] = Hash.new()
$States["California"]["Los Angeles"]["District 1"] = "90035"