Tuesday, April 18, 2006

Hash Auto-vivification

One of the more convenient (but sometimes bug-creating) features in Perl is autovivification: a variable is created just by referring to it (or, comes to life on its own). This is useful for creating composite data structures out of hashes or arrays-- for example, writing '$a{"a"}{"b"} = 3;' creates a hash of hashes called %a for you automatically.

Ruby doesn't have this "feature" by default, but like many other things in Ruby, you can work around it. Here's one neat way to autovivify hash-of-hashes, using recursion and Hash default procs (posted by Bill Kelly on ruby-talk):

HashFactory = lambda { Hash.new {|h,k| h[k] = HashFactory.call} }

irb(main):181:0> x = HashFactory.call
=> {}
irb(main):182:0> x['abc']['def']['ghi'] = 123
=> 123
irb(main):183:0> x
=> {"abc"=>{"def"=>{"ghi"=>123}}}


Awesome...

0 Comments:

Post a Comment

<< Home