From: Mark Hubbart Date: 2005-05-18T12:13:15+09:00 Subject: Re: Noobie ... Simple Inheriting from Hash Question .. On 5/17/05, David A. Black 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 cheers, Mark