Ruby Ruby Collections Ruby Hashes Working with Hash Values

has_value? method not working

The has_value? method does not work in this script-er.

hash.rb
grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }

if grocery_item.has_value?("Bread")
  grocery_item = { "food"=> true}
end 

2 Answers

Michael Hulet
MOD
Michael Hulet
Treehouse Moderator 47,024 Points

The has_value? method is actually working just fine here, and you're calling and using it correctly. It's what you're doing inside the if block that isn't right here. The challenge asks you to add a new key "food" inside that if block, but your current implementation overwrites the entire hash with a new one (which is what the assignment operator (=) does to variables). You can add a new key to a hash by assigning to subscript syntax, however, which looks like this:

some_hash = {key: 1}

some_hash[:new_key] = 2 # This is the line I'm talking about

# some_hash is now {key: 1, new_key: 2}

Once you change the line in your if block to use the subscript syntax instead of raw assignment, it passes the challenge just fine

Thank you.