From: Nikolay Pavlov Date: 2007-09-12T05:19:47+09:00 Subject: Re: alter_key function for Hash On Tuesday 11 September 2007 21:14:43 Daniel Schierbeck wrote: > On Wed, 2007-09-12 at 02:57 +0900, Nikolay Pavlov wrote: > > Hallo all. > > Of course i am reinventing the wheel, but may be that would be helpful > > for some one. With this method you can replace a key with a new one in > > a Hash. It could be helpful for example if you want to parse a lot of > > XML documents in hash from various external sources in one Library, so > > that you can handle a unified interface. > > > > class Hash > > > > # Replace an old key with a new one > > # > > # === Arguments: > > # * old_key > > # * new_key > > def alter_key(old_key, new_key) > > raise IndexError.new("key already exist") if self[new_key] > > if self.has_key?(old_key) > > self[new_key] = self[old_key] > > self.delete(old_key) > > end > > return self > > end > > end > > It can even be written more concisely as: > > class Hash > def alter_key(old_key, new_key) > raise IndexError, 'key already exists' if has_key? new_key > store(new_key, delete(old_key)) if has_key? old_key > return self > end > end > > > Cheers, > Daniel Schierbeck Thanks Danial. This is just a wheel :) -- ====================================================================== - Best regards, Nikolay Pavlov. <<<----------------------------------- ======================================================================