Ruby Ruby Collections Ruby Hashes Working with Hash Values

Edward A. Polanco Murillo
Edward A. Polanco Murillo
2,872 Points

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.

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

1 Answer

Jeff Muday
Jeff Muday
Treehouse Moderator 24,835 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_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"]