HELP: Iterating over hashes Ruby exercise 16


#1

This is my code:

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

lunch order.each do |order name, order|
  puts key, lunch order [order name, order]
end

Instructions
01 Iterate through .each key/value pair in lunch_order.
Please puts out the value of each pair (just the value, not the key).


#2

Simply change the puts statement to:

puts order

#3

Also, in this line:

lunch order.each do |order name, order|

order name is an invalid identifier. Identifiers cannot have space character in them.

And, lunch order instead of lunch_order is a typo there.


#4

Help me! This is my code:

lunch_order = {
  "Ryan" => "wonton soup",
  "Eric" => "hamburger",
  "Jimmy" => "sandwich",
  "Sasha" => "salad",
  "Cole" => "taco"
}
lunch_order = {
  "taco" => 4,
  "salad" => 3,
  "sandwich" => 2,
  "hamburger" => 1,
  "wonton soup" => 0
}

lunch_order.each do |lunch_order|
  print lunch_order [lunch_order]
end

it looks ok, but every time I try it the console gives me the error: can't convert Array into Integer. What do I need to change, the lesson texts aren't very helpful sadly :confused:


#5

You are using the same identifier for each variable!

The Ruby interpreter here assumes that one name belongs to only one variable so even if it sees something like this:

lunch_order = { # a unique name
  # some code
}
lunch_order = { # the same name as before??
     # some code
}

It assumes that if a name is being used again, it is definitely referencing the already-defined variable. So, your 2nd {} declaration is overwriting the first {} declaration.

Then, you do this:

lunch_order.each do |lunch_order|
  print lunch_order [lunch_order]
end

Here, the local variable lunch_order is shadowing/hiding the global variable lunch_order. That's why you are getting the error.

Solution to your problem is to rename the variables that have to store some new value.