This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this video, we're going to explore some of the methods that Ruby provides us for working with hashes.
Links
Code Samples
For the examples below, we'll be working with the following hash:
hash = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
The #length
method will return the number of keys in the hash. In this case, it would be 3:
hash.length
The #invert
method returns a new hash with the keys and values transposed:
hash.invert
That would produce the following new hash:
{"Bread" => "item", 1 => "quantity", "Treehouse Bread Company" => "brand"}
The #shift
method works similar to hashes as it does with arrays. It will remove a key and value pair from the hash and return it as an array:
hash.shift
This would return the following (note that it is an array):
["item", "Bread"]
The original hash would also be modified:
{"quantity" => 1, "brand" => "Treehouse Bread Company"}
The #merge
method combines the hash sent in as an argument and returns a new hash with the two combined:
hash.merge({"calories" => 100})
Would return the following:
{"quantity" => 1, "brand" => "Treehouse Bread Company", "calories" => 100}
If any key value pairs exist in the original hash, the merge
method will overwrite those:
hash.merge({"quantity" => 100})
Would return:
{"quantity" => 100, "brand" => "Treehouse Bread Company"}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up