Mark Hubbart wrote:
> On 5/17/05, David A. Black <dblack / wobblini.net> wrote:
>> Hi --
>>
>> On Wed, 18 May 2005, David Mitchell wrote:
>>
>>> You could just extend the hash class, rather than inheriting from
>>> it. That is, instead of this:
>>>
>>> class myHash < Hash
>>>       def foo
>>>               ...
>>>       end
>>> end
>>>
>>> Do this:
>>>
>>> class Hash
>>>       def foo
>>>               ...
>>>       end
>>> end
>>>
>>> Then, all your hash objects will be given your 'foo' method and you
>>> can do things like this:
>>>
>>> {:key => "value"}.foo
>>
>> This will work but also suffers from the usual problem with extending
>> core classes -- namely, it's unsafe to do unless you're sure
>> that your code will run in isolation.
>>
>> Another possibility is to add the behavior on a per-object basis:
>>
>>    module MyHashStuff
>>      def foo
>>        # ...
>>      end
>>    end
>>
>>    h = {1,2,3,4}
>>    h.extend(MyHashStuff)
>>    h.foo                  # h now has the food method
>
> Another option is to add a to_myhash method to Hash:
>
> class MyHash < Hash
>   def foo
>     ...
>   end
> end
>
> class Hash
>   def to_myhash
>     MyHash.new.update self
>   end
> end
>
> Now you can create myhashes like this:
>
> {1=>2,3=>4}.to_myhash

Note though, that this is exactly what the original poster tried to
avoid - the intermediate hash.

Another option that hasn't been mentioned yet is to use delegation.  You
can have a wrapper around a hash that contains all your additional methods
and references a Hash instance.

Kind regards

    robert