7/16 Iterating Over a Hash


#1

I'm iterating over a hash, attempting to print only the values in the key:value pairs.

Lesson Link

This is the error message: "Oops, try again. It looks like you didn't print anything to the console."

Here's my code:

lunch_order = {
    "Ryan" => "wonton soup",
    "Eric" => "hamburger",
    "Jimmy" => "sandwich",
    "Sasha" => "salad",
    "Cole" => "taco"
}

lunch_order.each { |x| puts lunch_order[x] }

In the earlier lesson, it said that in order to access the value in a key:value pair, you had to use bracket notation like this:

puts hash[x]

I'm doing the same thing here, aren't I? Thanks in advance for any help.


#2

When iterating over a hash, even if we only want to print the key, or the value, not both, we need to provide placeholder variables for both in the block parameter.

my_hash.each { |k, v| puts v }

#3

Thank you! That makes a lot more sense!