CodeNewbie Community 🌱

Cover image for 49 Days of Ruby: Day 10 - Hashes
Ben Greenberg
Ben Greenberg

Posted on • Originally published at dev.to on

49 Days of Ruby: Day 10 - Hashes

Welcome to day 10 of the 49 Days of Ruby! πŸŽ‰

Today is all about another important data type, the hash!

Yesterday, we discussed the Array data structure, and what you can do with it. The hash is similar to an array in that you can use it to hold data and access it. However, there are several important differences. Let's check them out!

What exactly is a Hash?

Whereas an array is an ordered collection of items, a hash is a collection of items stored in key and value pairs.

A Hash is unordered. This means that you access a value in the hash by using its key name instead of its index value.

Here is an example of creating a new Hash and accessing a value inside of it:

hash = { "coffee" => "Americano", "day" => "Tuesday" }

puts hash["coffee"]
# => "Americano"

Enter fullscreen mode Exit fullscreen mode

In the above example, we created a new hash with two keys: "coffee" and "day". We assigned two string values to those keys.

The value stored with the "coffee" key can be accessed inside the hash by directly referencing it in our #puts method: hash["coffee"]. In this case, that prints out the word "Americano".

Experiment With Hashes

Now it's time to play around with Hashes a bit!

Open up IRB in your terminal and let's create a hash:

irb(main)> hash = {"coffee" => "Americano", "day" => "Tuesday" }

Enter fullscreen mode Exit fullscreen mode

What can we do with that hash?

We can access the keys by invoking the #keys method:

irb(main)> hash.keys

# => ["coffee", "day"]

Enter fullscreen mode Exit fullscreen mode

Did you notice what kind of data structure the keys were returned to us in? The brackets are your hint! They came back to us in an Array.

We can access the values by invoking the #values method:

irb(main)> hash.values

# => ["Americano", "Tuesday"]

Enter fullscreen mode Exit fullscreen mode

The values also are returned in an Array.

What if you wanted to iterate over each value in a Hash? There's a method for that, too! You can use #each_value. And, if you had to guess about iterating over each key? Yes, you'd be right, that method is #each_key:

irb(main)> hash.each_value { |value| puts value }

Americano
Tuesday

# => {"coffee"=>"Americano", "day"=>"Tuesday"}

Enter fullscreen mode Exit fullscreen mode

What else can you do with Hashes? Check out the official Ruby docs on the Hash and try it out in your IRB session, and share your learning with hashtag #49daysofruby!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)