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
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"]
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