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"

9 comments:

  1. very good

    that is what I am needing

    regards

    ReplyDelete
  2. awesome, thanks, this is exactly what i was looking for.

    ReplyDelete
  3. thx a lot, exactly what I was looking for and works like a charm :-)

    ReplyDelete
  4. Yes, very nice...thanks for sharing

    ReplyDelete
  5. Thank you so much for this!! all of the examples elsewhere are so overly-complex. I knew there was a much more basic way that made sense! I don't know why programmers feel the need to show off with complex examples when much more basic ones exist

    ReplyDelete
  6. Nice! I been struggling creating dynamic nested Hash in Ruby. Your blog has helped me finally.
    Thanks!

    ReplyDelete
  7. that works! thanks!!!!

    ReplyDelete