# Alter\_key function for Hash

**URL:** <https://www.ruby-forum.com/t/alter-key-function-for-hash/114359>\
**Category:** Ruby\
**Created:** [September 11, 2007, 7:58pm UTC](https://www.ruby-forum.com/t/alter-key-function-for-hash/114359 "2007-09-11T19:58:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nikolay\_P](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f9ae1b/32.png) [@Nikolay\_P](https://www.ruby-forum.com/u/Nikolay_P)\
**Post date:** [September 11, 2007, 7:58pm UTC](https://www.ruby-forum.com/t/alter-key-function-for-hash/114359/1 "2007-09-11T19:58:28Z")

</div>

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

irb(main):006:0\> hash = Hash.new  
=\> {}  
irb(main):007:0\> hash[:old] = 10000  
=\> 10000  
irb(main):008:0\> hash.alter\_key(:old, :new)  
=\> {:new=\>10000}  
irb(main):009:0\> hash[:new]  
=\> 10000

---

<div class="post-metadata">

**Author:** ![Nikolay\_P](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f9ae1b/32.png) [@Nikolay\_P](https://www.ruby-forum.com/u/Nikolay_P)\
**Post date:** [September 11, 2007, 8:15pm UTC](https://www.ruby-forum.com/t/alter-key-function-for-hash/114359/2 "2007-09-11T20:15:31Z")

</div>

On Wed, 2007-09-12 at 02:57 +0900, Nikolay P. wrote:

> # 
> 
> 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 S.

---

<div class="post-metadata">

**Author:** ![Nikolay\_P](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f9ae1b/32.png) [@Nikolay\_P](https://www.ruby-forum.com/u/Nikolay_P)\
**Post date:** [September 11, 2007, 10:20pm UTC](https://www.ruby-forum.com/t/alter-key-function-for-hash/114359/3 "2007-09-11T22:20:25Z")

</div>

On Tuesday 11 September 2007 21:14:43 Daniel S. wrote:

> > # Replace an old key with a new one
> > 
> > ```
> > return self
> > 
> > ```
> 
> ```
> end
> 
> ```
> 
> end
> 
> Cheers,  
> Daniel S.

Thanks Danial.  
This is just a wheel 🙂
