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
Let's start working with hashes now. Hashes are created in a couple of different ways. A hash can be instantiated using curly braces or instantiating a new instance of the class.
Code Samples
Here's how to create a hash by instantiating a new instance of the Hash class:
item = Hash.new
Hashes can also be created by using curly braces:
{}
When creating a hash using curly braces, keys and values can also be specified:
item = { "item" => "Bread", "quantity" => 1 }
Hash keys can be almost any Ruby type. Here's an example of using symbols as hash keys:
item = { :item => "Bread", :quantity => 1 }
Hash keys can also be numbers. If we set the following hash key and value:
item[1] = "Grocery Store"
Our hash would look like this:
{ :item => "Bread", :quantity => 1, 1 => "Grocery Store" }
Once a hash has been instantiated, it is possible to add new hash keys and values by using the name of the hash, brackets containing the new key, an equals sign, and the new value for said key:
item["brand"] = "Treehouse Bread Company"
If you're using symbols as keys, there's a shorthand notation you can use. So if you're defining a hash like this...
item = { :item => "Bread", :quantity => 1 }
...you can move the colons after the symbols, and omit the arrows. This hash will be identical to the one above:
item = { item: "Bread", quantity: 1 }
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