From: Rob Biedenharn Date: 2008-06-05T08:42:00+09:00 Subject: Re: double assignation in a hash On Jun 4, 2008, at 7:23 PM, nico Itkin wrote: > hi ! > > I'm new to ruby, i'd like to know if it is possible to make the > following kind of assignation in a hash, like i used to do in php : > > a={} > a[:b][:c]="value" > > the goal for me is to create a hash by iterating on keys, like > > hash={} > [a,b,c].each do |k1| > [d,e,f].each do |k2| > hash[k1][k2] = afunction(k1,k2) > end > end > > this last code lead to a nil.[] error > > Could you help me ? . Your problem is that a[:b] is not a hash. You can get this effect by defining a default for the hash 'a' like so: irb> a = Hash.new {|h,k| h[k] = {} } => {} irb> a[:b][:c] = 'value' => "value" irb> a => {:b=>{:c=>"value"}} The block supplied to Hash.new is called with the hash and the key when the key doesn't exist. So the effect is as if you had: a = {} a[:b] = {} a[:b][:c] = 'value' -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com