Ruby Ruby Collections Ruby Hashes Working with Hash Values

Daniel Springer
PRO
Daniel Springer
Pro Student 5,090 Points

Is there a better way to solve this challenge?

Given this challenge is there a shorter more efficient way to solve this?

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

1 Answer

William Li
PRO
William Li
Pro Student 26,785 Points

Personally I'd solve the part 1 this way

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

Actually, your code should've failed if the test cases have done a better job checking for correction. Because part 1 asks that a key-value pair "food" => true to be set in the Hash only if grocery_item.has_value?("Bread") is true; your code would also insert "food" => false into Hash when that condition is false.