Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
So far, we've learned how to create and modify hashes and work with hash keys. Ruby provides several ways to work with the values in a hash as well. In this video, we'll explore different ways to work with the values in a hash.
Code Samples
For the examples below, we'll be working with this hash:
hash = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
To return an array of the values in the hash, we can use the values
method:
hash.values
Which would return the following:
["Bread", 1, "Treehouse Bread Company"]
The has_value?
method takes one argument and returns true
or false
if the value is contained within the hash:
hash.has_value?("brand")
That would return false
since "brand" isn't a value. However, the following would return true
:
hash.has_value?("Bread")
The values_at
method takes several arguments and returns the hash values at the specified keys as an array:
hash.values_at("quantity", "brand")
That would return:
[1, "Treehouse Bread Company"]
-
0:00
Similarly, the hash keys, Ruby provides us methods for working with hash values.
-
0:07
Let's take a look of some of those now using WorkSpaces.
-
0:10
Okay, so I've just created a new ruby WorkSpace here and
-
0:14
here we are in the console.
-
0:15
Let's go ahead and launch an RIB session and start working with hash values.
-
0:21
So let's create a hash to work with.
-
0:24
The item here is gonna be bread, quantity of 1 and
-
0:29
the brand is still gonna be Treehouse Bread Company.
-
0:37
All right, so here is a hash to work with.
-
0:40
Now just like the method for looking at all the keys was called hash dot keys,
-
0:46
we have a similar method to look at all the values called values.
-
0:51
And that will return an array of all of the different values inside of the hash.
-
0:57
And again how we asked the hash if it had a key, and passed in an argument.
-
1:03
We can do the same thing to see if it has a value.
-
1:06
So we could say hash.has_value, and
-
1:09
then pass in a value it does not have the value brand because that's a key, but
-
1:15
let's see if it has a value for the number one which is the quantity and it does.
-
1:25
And we can also use the method value and pass in an argument.
-
1:30
It's pretty much the exact same thing, an alias under a different name.
-
1:36
If we wanted to get a couple values back from the hash,
-
1:39
we could use the values add method and pass in the keys that we want.
-
1:45
We'll say we want item and quantity and
-
1:48
that will return an array of the values for the keys that we passed in.
-
1:54
Try practicing with hashes and hash values on your own now using WorkSpaces.
You need to sign up for Treehouse in order to download course files.
Sign up