Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
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 up-
christopher vaughan
1,411 Points1 Answer
-
Jasmin Parent
4,311 PointsI have a problem with the workplace, typing is in some sort of insert mode and its not fixed by pressing insert key
Posted by Jasmin ParentJasmin Parent
4,311 Points0 Answers
-
A X
12,842 Points1 Answer
-
A X
12,842 Points1 Answer
-
SZE XU
1,053 PointsHi I am new to Ruby & programming, so whats the difference between array and hash in Ruby?
Posted by SZE XUSZE XU
1,053 Points2 Answers
-
Craig Garner
25,732 Points0 Answers
-
lindseyk
4,506 PointsComing from first learning Python, the concept of a "symbol" is confusing to me. Can someone clarify?
Posted by lindseyklindseyk
4,506 Points2 Answers
-
Sean Flanagan
33,236 Points1 Answer
-
Jess Claussen
6,078 Points4 Answers
-
Ali Amirazizi
16,087 Points1 Answer
View all discussions for this video
Related 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