alter_key function for Hash

N

Nikolay Pavlov

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[:eek:ld] = 10000
=> 10000
irb(main):008:0> hash.alter_key:)old, :new)
=> {:new=>10000}
irb(main):009:0> hash[:new]
=> 10000
 
D

Daniel Schierbeck

--=-9iMRoyMdEWA2FQBJFpVm
Content-Type: multipart/signed; micalg=pgp-sha1; protocol="application/pgp-signature";
boundary="=-byyM+bFcwYHV1sWC1M9G"


--=-byyM+bFcwYHV1sWC1M9G
Content-Type: text/plain
Content-Transfer-Encoding: quoted-printable
 
N

Nikolay Pavlov

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 :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,264
Messages
2,571,323
Members
48,006
Latest member
MelinaLema

Latest Threads

Top