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
Hashes are composed of keys and values. In this video, we'll learn how to work with hash keys.
Code Samples
Here is the hash we'll be working with:
hash = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
Keys
To find out all of the different keys inside of the hash, we can use the keys
method:
hash.keys
This would return an array of the keys in the hash:
["item", "quantity", "brand"]
To check whether or not a hash contains a key, we can use the has_key?
method, which returns true or false. It is aliased as member?
and key?
:
hash.has_key?("brand") # => true
hash.member?("quantity") # => true
hash.key?("item") # => true
The store method will add a key and value pair to a hash:
hash.store("calories", 100)
The hash would then contain the following:
{ "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company", "calories" => 100 }
Equality
Two hashes are considered equal when they have the same keys and values:
milk = { "item" => "Milk", "quantity" => 1, "brand" => "Treehouse Dairy" }
puts milk == hash # => true
bread = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
puts hash == bread # => false
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