Sign In | Subscribe
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Introduction to Ruby
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Bookmark and Share

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for Educator.com

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!

Hashes

  • Hashes are an unordered collection of key-value pairs that associate a value with each key
  • Hashes are accessible by keys or by values
  • The keys in a hash must be unique if the key is not specified it will return nil
  • A new hash can be created using the Hash.new constructor or {}
  • The hash can be iterated through using the each_key or each_value method
  • A hash can be converted to a array with to_a method and to a string using the to_s method

Hashes

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Hashes 0:12
  • Creating Hashes 1:18
    • Setting a Default Value
  • Accessing Hashes 4:16
    • Accessible by keys or by values
    • Keys must be unique
  • Creating Hashes 5:16
    • Comma-separated list
    • Hash rocket
    • Examples
  • Iterating Keys and Values 11:43
    • each_key
    • each_value
  • Merging Hashes 16:10
    • merge(other_hash)
  • Sorting Hashes 18:46
  • Replacing Hashes 20:57
    • replace(other_hash)
  • Converting Hashes to Other Classes 22:04
    • to_a
    • to_s
    • Example
  • Check Out the Earlier Lesson 27:22
    • Ruby Data Types Part 2

Transcription: Hashes

Welcome back to Educator.com.0000

Today's lesson is on hashes.0002

What are hashes? Hashes are unordered collections of key-value pairs.0009

They maintain a set of objects known as keys, and each key is associated with a value.0020

Think of it this way: think of a hash as kind of like a table.0033

In this table, you have two ways to look up the values: one way is through keys, and another way is through values.0046

This pretty much sums up how the hash is created.0061

How do we create a hash? You can create a hash in many different ways.0077

The first way is through the constructor--just using hash.new.0084

This is using the normal .new method.0089

The other way, which is more commonly used, is through the curly brackets, which you will see in other languages, too.0098

This is method 1...number 1 and number 2.0108

This is probably the preferred way you will actually see it being created.0112

With the hash, you could also pass in an argument, and if you pass in an argument, it will actually set a default value to your hash.0122

So, if I create a new key, and I were to access it, you would actually see it as a default value if there isn't one that already exists.0130

For example, I have this hash.new, and my default value I'm passing in is the default value 0.0140

Notice: I have this new hash; I haven't declared any keys yet; but then, I'm actually assessing new_key, and it says, "I'm going to give you the default value of 0."0152

You can also...notice that this is optional, but this is our default value here.0170

Now that we have created our hash, and we know how to make a default value for it, we can also run some common hash methods to say, "Is this a new hash?"0194

"Is this hash new? Are there elements in this hash?"0208

One thing we can use is this method called empty?.0212

If you call newhash.empty?, it's going to return true, because we haven't actually added any keys or any values to it.0219

This returns true if there are zero keys.0230

Another method you could look at is this size method.0237

It also returns 0, because there are no keys or values in this hash yet.0244

Now, we are going to look at accessing the hashes.0256

There are many methods and ways to do it.0260

You can access the hash by the key or by the value.0266

These keys must be unique.0272

You can't have a hash with two different types of keys; if you do that, one is going to take precedence over the other, and, in this lookup table of keys, you are only going to have one.0278

It's going to overwrite what is currently existing there if you try to add a second key.0291

By default, keys that do not exist will return nil.0299

You will notice that, in our last slide, we set a default value so it wasn't returning nil--it was returning 0.0305

To create this hash, another way I could do it is using these square brackets.0315

This is kind of an interesting thing just in Ruby; it allows me to use the square brackets and create a value order, and it will create a hash from it.0327

To do this, essentially, I'm going to call a code piece...I call hash--key word--and then, in the square brackets, I'm going to give it an order of the key, the value, the key, the value...and I'm going to continue down that whole list.0340

Notice that this will be an array that has an even number of elements, because of this ordering.0375

When I create the hash using these square brackets, then it's going to convert that to a real hash.0389

For example, I'm using the exact same syntax you see here with the hash square brackets: my first key value here is 2016, and then my value is Brazil.0397

I'm creating a hash of all the Summer Olympics, from newest to oldest.0414

The next one is 2012--that is my key--and my value is London.0420

Let me put a little 1 here, so we know where they are going to.0430

And then 2008--that is a key again--Beijing is a value...this was actually 3; then key--2004: Athens is a value.0438

Notice, after I do this, I push Return; it is going to convert this square in square brackets--the array--and it will make that a Hash.0457

So, we have our hash here.0477

Notice that it automatically converted it to these key-value pairs to follow our hash syntax.0481

Another way you can create this hash is using the curly brackets.0503

We already saw how to do it using the constructor.0510

Now, we can also create the hash by defining the values in there.0513

This is going to make exactly the same end result as the square brackets, but this is a more common way that hashes are built.0518

Let me add here "commonly used"...because it's commonly used in Ruby.0530

Again, we use the exact same thing; notice here, instead, we are using this hash rocket here; this is my hash rocket: it says...I have this key, 2016, but it is pointing to its value, Brazil.0548

I'm using this hash rocket continuously with these key-value pairs: 2012 to London, 2008 to Beijing, 2004 to Athens...and after you press Return, it is going to return you the exact same thing, because you have already defined the hash.0569

It's going to say, "OK, your Summer Olympics points to a hash reference, and here are the values to it."0585

You can also add spaces to this, so you don't have to have all of this in one line.0595

Your coding might be more organized, also.0605

Let me show you how you do that.0608

I have my Summer Olympics, and notice, in my code, I'm going to start off with the first curly brace.0612

I press Return; it doesn't actually end the code--the code will continue--and now I can make it more easily readable.0628

So, I can put here...2016...have my hash rocket...Brazil.0637

Come down to 2012--London.0644

I continue down to Beijing...and 2004, Athens.0649

As you see, the end result: it's going to return the end hash that I created.0662

Also, if I do Summer Olympics, and I just do Return, it also returns the same hash reference.0670

As you can see, Ruby allows me that flexibility; I can add those newlines, those break lines, and I'm still defining the same hash.0680

It just makes it easier for me to code this up--and it makes it easier for people to read, too, which is nice.0690

OK--we went through a lot of hash creation here; let's go back to accessing these hashes.0704

We're going to look at iterating these keys and values.0712

I have my hash already; I've defined it; I have my values; now I'm going to start accessing these keys and values.0716

The first thing I want to do is look at a method called each_key.0723

This goes through my hash, and I can go through all of the different keys in it, and I can do my own code manipulation to what I want to do with it.0729

To do this, you call your hash, hash method each_key, and you pass in these curly braces, and in there, one argument you will get is key, and then block is your actual code.0739

This is going to go through each of your keys and pass in that key value with it, and then, in your code block, you can manipulate it, store it somewhere else...do whatever changes you need to do.0757

It will iterate through your keys, passing key as the parameter--and this is your key as your parameter, right here.0773

For example, we are going through a hash of colors.0783

Again, I have my hash rocket; 1 is defined 'blue', 2 points to red, 3 to yellow, 4 to green, 5 to black.0791

If I run the BestColors, and I just call method each_key, it's going to say that I want to print the keys, one by one.0803

It's first going to print the first key, 1; then it's going to print 2, 3, 4, and 5.0816

After I return, you will notice that the end result is that it's going to show the output 1, 2, 3, 4, and 5.0828

In the same way you have each_key, you also have a method called each_value.0844

With the each_value...it goes through each value, one by one.0849

You have your list of values, and it ignores the key; you're just going to go through all your values.0853

Same thing: here is your method; your parameter is val; and the block it's defined to.0862

Now, the val is something I've defined; you could actually call it something else, but that parameter, val, will be your value.0873

Let's go through an example with the BestColors again--the exact same example I just showed you.0884

For our code block here--let's put this as our code block...this is our val, and each value--notice how this, down here, matches up with the syntax up there.0890

Our code block says, "I want you to print the value, and then append a space there."0913

I press return; the first thing it's going to do is to print out the first value, blue; add the space; red; space, yellow, green, and black.0922

You take this code; you put it in your IRB; press Return; the result will be blue, red, yellow, green, and black.0938

Pretty easy, huh? It's pretty simple, but it's nice to know that you have these methods to handle these things and get things out of the hash that it wouldn't normally do.0953

Next, let's look at merging hashes.0966

We have this method called merge: it takes in a parameter called other_hash.0970

I call it other_hash; it just takes in another hash, OK?0978

This method will return a new hash that contains the contents of your other hash and your self.0982

It's going to merge them together.0992

Duplicate keys will return the other_hash entry.0994

So, I have my hash here in a, and I'm merging hash b: b takes precedence--that is what it means.1000

Let's look at an example.1012

I have a hash called NorCal and one called SoCal.1015

In my NorCal hash, I have the key value 1 going to San Francisco, 2 to Sacramento, and 3 to San José.1019

For SoCal, I have 4 going to Los Angeles, 1 to San Diego, 6 to Anaheim, and 7 to Irvine.1030

Notice one thing: San Diego has a key 1, and NorCal has a key 1, so there is a conflict here: they have the same key.1039

Now, here in my code, I'm going to call NorCal.merge(SoCal), and I'm creating a new hash called California.1052

I press Return on that: the end result: 1 is going to point to San Diego, 2 to Sacramento, 3 to San José, 4 to Los Angeles, 6 to Anaheim, and 7 to Irvine.1063

There is no SF anymore; SF was removed.1080

Since we merged the SoCal key with San Diego in, that has overridden SF; so it removed that key-value pair altogether.1088

There is no more of this key-value pair here.1102

But notice that, now, we have a bigger hash that combined the two.1109

Next, let's look at sorting hashes.1123

To do this, I have a method called sort: it has two parameters--I'm just calling a and b here, and then you have your normal code block--whatever you want to sort it with.1126

This sort method is extended from Enumerable, and this allows you to sort elements using the Enumerables' sort method here--the less than, equals, greater than sign.1138

For this, we have NorCal: I have my example here again--I have three cities in NorCal: 3 points to San Francisco; 2 to Sacramento; 1 to San José.1155

I do puts; it's going to output that; I'm going to have my hash.1169

But now I want to sort it, but I want to sort it by value.1173

So, I take this structure here, and I'm going to follow that down here--notice, here I have the exact same structure.1179

I have my key-value pairs, a, b, and when I put this [1], that's going to say, "Look at the value, because I want to sort by that value."1194

The end result is: if I press Return on that, Sacramento is going to be first, San Francisco next, and then San José.1208

Also, if I were to use a, zero, b, zero, I could also use that to sort by key.1222

So, depending on your code, that might be more significant.1243

Let's now look at a new method called replace.1255

This is for replacing your hash; it takes your original contents, and it replaces them with the new contents of this other hash.1262

So--overwrites the contents of self with the contents of other_hash...1272

For our example here, I have a hash of three key-value pairs, a, b, c, and then I call the .replace method.1277

I have: a points to 1, c to 500, d to 550--and you will notice that the end result has...the value hash has...only these new elements in there.1291

These two hashes are the same, and the contents of the original one are gone.1308

That is what this method, replace, does.1320

Let's go ahead and look at converting the hash to other classes.1325

First, let's look at the Array class.1332

You have this to_a; if I call this on a hash, it will convert that hash to an Array.1336

We have an example here: I have my hash, a hash of fruits; the a key goes to apple, b to banana, c to carrots.1344

I call .to_a, and it will actually create a multidimensional Array.1355

I have an Array of an Array.1361

Notice, I have a, apple; b, banana; c, carrots; these are my original key-value pairs in the hash, but now they are Arrays of two elements.1373

The next one we will look at is converting to a string.1394

To do that, we have this method called to_s.1402

This is the same method as inspect; if I were to call inspect or .to_s, it would do the identical, same thing.1406

This converts it to a string.1413

For this example, what I wanted to do is take this hash and convert it to a string, but make it really clean, so I actually chained a bunch of methods here...so I'm using some chaining...1416

I have my original hash; then I call a bunch of different methods: I call to_s first to convert it to a string; then I call this gsub method, which is going to remove a lot of stuff that I don't need--that I wouldn't visually be able to see.1435

Then, I call this split method to break it down by the comma and the space.1454

Now, I do want to show you this example to show you how it's doing this, so let's go to our terminal.1463

First, let's go ahead and create our Array.1475

Let's make it even cleaner here; I'm going to use some newlines.1482

OK, so I first created my hash; I'm going to do Foods.to_s.1496

You will notice that I have a lot of stuff here: you have your backward slashes to help escape out those quotes, and you have actual quotes in front of that, and I don't need that, because visually, this does not look clean.1503

I want to remove some of those weird characters.1520

I'm going to create a new variable called nomoreweirdcharacters, and then I'm going to call that again with a string; then I'm going to call my gsub method, and with my gsub, what I want to do is just remove those out of the way.1524

Let's see here--first, I'm going to remove that quote; then I'm going to remove that curly brace, the other curly brace...and let's see if this does it.1541

So, I said to remove the quote, the left curly brace, the right one, and it's a regular expression literal...let's see if that does it.1558

Yes! So, now I have my variable without those characters anymore, but then I want to break it down into an Array so it breaks it out more.1569

OK, call my split...there you go--that will remove that.1597

The end result: we have an Array of three elements; it still has my hash rocket in there, and it looks nice now.1609

That ends up this chaining method, and you got to see that to_s in effect, plus some more methods to massage it even further.1629

Otherwise, that is the end of today's lesson on hashes.1644

Be sure to check out Ruby Datatypes Part 2, where we do go over a lot of the basics of hashes, and it will get you up to speed even further in the hash realm.1649

Thank you for watching Educator.com, and see you next time!1665