On 05.02.2010 06:01, Kirk Haines wrote:
> On Thu, Feb 4, 2010 at 7:33 PM, Mr Bubb<jcabraham / gmail.com>  wrote:
>> Well, in my job (bioinformatics), I only use code like this about a
>> hundred times a day. I've been doing this job for 15 years, and
>> actually, there is no better way. You must not need to quickly create
>> data structures from flat files, I guess.
>
> Let me know if my detailed explanation didn't make sense.  The long
> and the short of it is this:
>
> auto_nesting_hash = Hash.new {|hash,key| hash[key] =
> Hash.new(&hash.default_proc)}

IMHO this is the most concise and elegant way to do it in Ruby!  I am 
surprised you are the only advocate of this.

> Just as a quick example, there was a thread last week where someone
> was asking about while loop performance, and wondering why a while
> loop in Ruby isn't so fast as he expected.
>
> i = 0
> while i<  10000000
>    i += 1
> end
>
> Perfectly legitimate Ruby, and comparable to similar looping
> structures in other languages.  But, the real answer there is that
> there's another way to do it in Ruby that's substantially faster.
>
> 0.upto(10000000) {|i| #do whatever you need to do with i }

This one does one iteration more than the original code if I'm not 
mistaken.  There's also

10000000.times {|i| #do whatever you need to do with i }

> So, if the auto nesting hashes work for you, that's great.  If you
> want to bend people's minds towards perhaps suggesting a better
> alternative, though, provide more details. Someone may surprise you
> with something unexpected, and superior.

Just as a vague idea: a similar thing could be created with OpenStruct 
accesses - saves you a lot of typing of [].  Then you could do 
hash.foo.bar.baz = 123

class AutoNest
   def method_missing(s,*a,&b)
     case s
     when /\A(\w+)=\z/
       class <<self;self;end.class_eval { attr_accessor $1 }
       send(s,*a)
     when /\A\w+\z/
       class <<self;self;end.class_eval { attr_accessor s }
       x = self.class.new
       send("#{s}=",x)
       x
     else
       super
     end
   end
end

hash = AutoNest.new
hash.foo.bar.baz = 123
p hash, hash.foo.bar.baz

I'd probably stick with your solution though.

Kind regards

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/