Skip to content

Instantly share code, notes, and snippets.

@corey
Forked from cloudspace/hsh.rename_keys
Created June 19, 2009 16:16
Show Gist options
  • Save corey/132709 to your computer and use it in GitHub Desktop.
Save corey/132709 to your computer and use it in GitHub Desktop.
class Hash
# Accept a hash of values, changes the value in self
# from the key in the param to be indexed at the value of param
# and returns the new hash. Does not modify self.
#
# >> a = {"dog" => "meow", "bird" => "tweet" }
# => {"bird"=>"tweet", "dog"=>"meow"}
# >> a.rename_keys "dog" => "cat"
# => {"cat"=>"meow", "bird"=>"tweet"}
# >> a
# => {"bird"=>"tweet", "dog"=>"meow"}
def rename_keys(list)
a = dup
list.each_pair do |from, to|
a[to] = a.delete(from)
end
a
end
# Same as hsh.rename_keys except it operates directly on self
def rename_keys!(list)
list.each_pair do |from, to|
self[to] = self.delete(from)
end
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment