From: ts Date: 2001-04-18T01:49:56+09:00 Subject: [ruby-talk:13768] Re: Odd Hash Behavior (long) >>>>> "S" == Steve Tuckner writes: S> I am kind of new to Ruby, could you explain the change to the hash class in S> detail (it might be good for other newbies too)? I'll try but personnally I'm not good in english :-) S> pigeon% cat b.rb S> #!/usr/bin/ruby S> class << Hash S> alias :old_new :new it create an alias old_new on the method new (i.e. it save the old definition of new in old_new) S> def new(default = nil, &block) it redefine the method Hash::new which can take an optional argument and can be called with a block (as an iterator) S> a = old_new(default) it call the old definition of new S> if block_given? if Hash::new was called with a block S> raise "Invalid call" if default S> a.instance_eval <<-EOT it will redefine the method [] only for this object S> @block = block it save the block given to #new in an instance variable (specific to this object) S> alias :aref :[] S> def [](a) redefinition of [] S> if ! has_key?a if the key don't exist, it call the block and store the result in the hash S> self[a] = @block[] S> end S> aref(a) it retrieve the value (call the old method []) S> end S> EOT Guy Decoux