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

Daniel Springer
PLUS
Daniel Springer
Courses Plus 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
PLUS
William Li
Courses Plus Student 26,868 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.