Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Collections Ruby Hashes Working with Hash Values

J Quinn
J Quinn
2,439 Points

Need someone to explain directions more for this problem as I am unsure what to do.

See code:

hash.rb
grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company", "food" => true }
grocery_item.has_value?("Bread")

grocery_list = grocery_item.values_at(0)

2 Answers

Marco van Vemden
Marco van Vemden
12,553 Points

Hi J,

Task 1: The idea is to build a conditional statement (if) that uses the boolean result of the .has_value?("Bread"). If the condition is true, you add an item to the grocery_list hash containing the key "food" and the boolean value true.

Task 2: Using the values_at method, create an array called grocery_list with the value of the grocery_item hash at the "item" key. Note: The values_at method returns an array containing the values associated with the given key(s).

Here is how I solved Task 1 and Task 2:

grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
# Task 1
if grocery_item.has_value?("Bread")
  grocery_item['food'] = true
end

#Task 2
grocery_list = grocery_item.values_at("item")

Let me know if things are not clear. Please note that when solving a challenge, the code of Taks 1 should not be overwritten when solving Task 2.

J Quinn
J Quinn
2,439 Points

Using the values_at method, create an array called grocery_list with the value of the grocery_item hash at the "item" key.