Home »
Ruby Tutorial
Ruby Hash.transform_keys Method
By IncludeHelp Last updated : December 01, 2024
In this article, we will study about Hash.transform_keys Method. The working of this method can be predicted with the help of its name but it is not as simple as it seems. Well, we will understand this method with the help of its syntax and program code in the rest of the content.
Description and Usage
This method is a public instance method that is defined in the ruby library especially for Hash class. This method works in a way that it runs the provided block at least once for each hash key and returns a new hash. An enumerator will be returned if you are not providing any block along with the method at the time of its invocation.
This method does not bring change in the actual hash because this method belongs to the category of non-destructive methods.
Syntax
Hash_object.transform_keys
or
Hash_object.transform_keys{|key| block}
Parameters
This method does not accept any parameter instead you can provide a block for a better implementation.
Example 1
=begin
Ruby program to demonstrate transform_keys method
=end
hash1={"color"=>"Black","object"=>"car","love"=>"friends","fruit"=>"Kiwi","vege"=>"potato"}
puts "Hash transform_keys implementation"
hsh = hash1.transform_keys{|key| key+key}
puts "Value hash is #{hsh}"
puts "Self hash object : #{hash1}"
Output
Hash transform_keys implementation
Value hash is {"colorcolor"=>"Black", "objectobject"=>"car", "lovelove"=>"friends", "fruitfruit"=>"Kiwi", "vegevege"=>"potato"}
Self hash object : {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato"}
Explanation
In the above code, you can observe that we are updating the keys of the hash object with the help of the Hash.transform_keys() method. You can see that all the keys are updated by their names. This method is not creating changes in the actual hash object because this method is one of the examples of non-destructive methods.
Example 2
=begin
Ruby program to demonstrate transform_keys method
=end
hash1={"color"=>"Black","object"=>"car","love"=>"friends","fruit"=>"Kiwi","vege"=>"potato"}
puts "Hash transform_keys implementation"
hsh = hash1.transform_keys
puts "Value hash is #{hsh}"
puts "Self hash object : #{hash1}"
Output
Hash transform_keys implementation
Value hash is #<Enumerator:0x00005610dc177dc8>
Self hash object : {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato"}
Explanation
In the above code, you can observe that when we are invoking the method without passing any block then the method is returning an enumerator.