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
Hashes have several different ways of iteration -- keys, values, and both keys and values at the same time. Here, we'll learn how to use Ruby to loop through or iterate over a hash, using methods like "each."
Documentation Links
Code Samples
The following code samples will use this hash:
business = { "name" => "Treehouse", "location" => "Portland, OR" }
We can work with each key and value using the each
method, which takes two arguments. We separate arguments to blocks using a comma, just like method arguments:
business.each do |key, value|
puts "The hash key is #{key} and the value is #{value}."
end
The each
method is aliased as each_pair
.
We can iterate over hash keys using the each_key
method, which takes one argument:
business.each_key do |key|
puts "Key: #{key}"
end
The same thing applies to values using the each_value
method, which also takes one argument:
business.each_value do |value|
puts "Value: #{value}"
end
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