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

question about second part of this challenge.

I figured out that the second part of the challenge was

grocery_list = grocery_item.values_at("item")

but I am little confused as to why you needed to use the values_at instead of the has_value?. shouldn't the values_at take two indexes? while the has_value? takes in 1 value. I am just a little confused about it. plus testing on the irb after creating a hash to practice and then use the values_at? I kept getting back [nil] as my answer.

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

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

I agree-- Challenge part 2 is slightly odd. If I were to guess what he wants to accomplish is that the student should know how to use the has_value?() method and the values_at() method. The values_at() method is pretty handy in that you can return multiple values from a hash by supplying multiple keys (hence it returns a list).

The values_at() method (at least to me) seems to be rarely used by programmers.

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

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

grocery_list = grocery_item.values_at('item')

The values_at() method is pretty cool in that you can return an ordered array. For example. If I wanted to get the grocery_item brand and item name, I can choose the order-- see below. First I get an array that has the brand first and the item second. After that, I show that I can get the item name and then the brand.

irb(main):026:0> grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
=> {"item"=>"Bread", "quantity"=>1, "brand"=>"Treehouse Bread Company"}
irb(main):027:0> grocery_item.values_at('brand', 'item')
=> ["Treehouse Bread Company", "Bread"]
irb(main):028:0> grocery_item.values_at('item','brand')
=> ["Bread", "Treehouse Bread Company"]
irb(main):029:0>