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

Richard Barkinskiy
Richard Barkinskiy
10,663 Points

values_at method not working correctly...

The following code need to store "Bread" inside the new array grocery_list. The code looks good to me, but I'm still receiving an error. Anyone know why? Thank you

hash.rb
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")]

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Hi, Richard, I answered the same question about 15 minutes ago in another post https://teamtreehouse.com/forum/im-not-sure-i-quite-understand-what-it-is-theyre-looking-for

The problem of your solution

grocery_list = [grocery_item.values_at("item")]

Is that values_at method return an Array, so [grocery_item.values_at("item")] will give you a multidimensional Array [["Bread"]], that's why it didn't pass the grader.

Richard Barkinskiy
Richard Barkinskiy
10,663 Points

I see in your previous answer you suggested the following:

grocery_list = Array.new(grocery_item.values_at('item'))

How is that different than what I have?

William Li
William Li
Courses Plus Student 26,868 Points

Array.new and [] are constructor and literal ways of creating array object in Ruby, most of time you can think of them as the same thing and use interchangeably, but on some occasion, there're differences.

a1 = [[1,2,3]]  #=> [[1,2,3]]
a2 = Array.new([1,2,3])  #=> [1,2,3]

But when writing real world Ruby code, this difference doesn't matter, why? Because when you need to assign an Array to a variable, you just assign it a = [1,2,3] like that, you don't need a constructor or Array literal to do the job.

So for this problem

grocery_list = grocery_item.values_at('item')

is the way to go.