On Nov 22, 2005, at 5:45 PM, Bill Kelly wrote:
> @attributes = Hash.new {|h,k| h[k] = Array.new}
Hey, thanks for that! I had no idea that the block form of Hash
creation had block arguments. Sure it's in 'ri', but who looks there? ;)
I often see people suggesting:
Hash.new{ [] }
without realizing that this doesn't set the value on the hash, just
returns a blank array. I've never been able to use the block
constructor syntax because it was so useless (because I also didn't
know that <<= was a valid compound method).
foo = Hash.new{ [] }
foo[:bar] << 1
foo[:foo] << 2
foo[:bar] << 3
p foo
#=>{}
foo = Hash.new{ |h,v| h[v]=[] }
foo[:bar] << 1
foo[:foo] << 2
foo[:bar] << 3
p foo
#=>{:bar=>[1, 3], :foo=>[2]}
foo = Hash.new{ [] }
foo[:bar] <<= 1
foo[:foo] <<= 2
foo[:bar] <<= 3
p foo
#=>{:bar=>[1, 3], :foo=>[2]}