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 Build a Grocery List Program Build a Grocery List Program: Part 1

Array.new?

why did you decide to use Array.new for the value in the items key when creating a hash.

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

A shopping list is represented as an array of hashes.

A list is another name for an array. You can declare a new list as empty square brackets or use "Array.new". These are equivalent methods. See below. bag1 is declared with square brackets, bag2 is declared with Array.new. They function exactly the same.

irb(main):001:0> bag1 = []
=> []
irb(main):002:0> bag2 = Array.new
=> []
irb(main):003:0> item1 = {'name'=>'bread','quantity'=>1}
=> {"name"=>"bread", "quantity"=>1}
irb(main):004:0> item2 = {'name'=>'apples','quantity'=>4}
=> {"name"=>"apples", "quantity"=>4}
irb(main):005:0> bag1.push(item1)
=> [{"name"=>"bread", "quantity"=>1}]
irb(main):006:0> bag2.push(item1)
=> [{"name"=>"bread", "quantity"=>1}]
irb(main):007:0> bag1.push(item2)
=> [{"name"=>"bread", "quantity"=>1}, {"name"=>"apples", "quantity"=>4}]
irb(main):008:0> bag2.push(item2)
=> [{"name"=>"bread", "quantity"=>1}, {"name"=>"apples", "quantity"=>4}]
irb(main):009:0>