From: Ken Bloom Date: 2007-11-04T10:40:03+09:00 Subject: Re: x=[]; x[:bla][:some_key] does not work? On Sat, 03 Nov 2007 15:44:48 -0500, sepp2k wrote: > Joshua Muheim wrote: >> PHP lets me easily create multidimensional hashes[...] Is Ruby not >> capable of doing this? >> >> x = [] > > That's an array. A hash would be x={} > >> x[:bla][:some_key] = true >> >> gives me a nil error! > > The code above should give you a different error. If you use {} it > should give you a nil error because x[:bla] would return nil and nil > doesn't have a method []. > To fix that you have to make x return a hash for non-existant keys. That > would work as such: > x = Hash.new {|h,k| h[k] = Hash.new} > x[:bla][:some_key] = true > > Or if you want an arbitrary amount of nesting: > > blk = lambda {|h,k| h[k] = Hash.new(&blk)} x = Hash.new(&blk) > x[:la][:li][:lu][:chunky][:bacon][:foo] = "bar" > > > HTH, > Sebastian Or use Hash#autonew from the facets gem, which does precisely the same thing. --Ken -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/