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

Simon Goldman
Simon Goldman
1,028 Points

array added to a hash

i have no idea how to even right this part of the code?? (im lost at this point)

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

Stefan Frank
Stefan Frank
5,990 Points

Hi Simon,

I think Tasks 1 isn't passing, because you got Tasks 2 wrong. So let's fix that:

  1. Make sure that you call the key itself [hash_name.has_value?("key")] and not the index, when you use values_at. I don't think that hashes are sorted in Ruby, so they don't have an index.

  2. You don't need "def" here. With "def" you create a new method.

  3. Use "grocery_list" as a new variable and then assign the "grocery_item.values_at("item")" inside of two brackets [] to that variable. With those two brackets you create the array and by adding the values_at part inside of it, it automatically adds those values to the array.

Here is my solution:

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

if grocery_item.has_value?("Bread")
  grocery_item["food"] = true
end

grocery_list = [grocery_item.values_at("item")]
Stefan Frank
Stefan Frank
5,990 Points

Hi Simon,

As you have seem to have found the right answer for Tasks 1 already, you are talking about Tasks 2 of the challenge, right?

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

It asks you to use the values_at method Ruby-Doc, which returns an array with the values associated with the given key.

You want to find the value associated with the key "food" of the "grocery_item"-hash. The value is going to be "true", as you have created it in Tasks 1 of the challenge. value_at already returns an array, you just have to assign the returned value to the variable "grocery_list".

Simon Goldman
Simon Goldman
1,028 Points

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

def grocery_list.values_at(0) end

it keeps on saying that that task one is no lionger passing when i put through the code??