Ruby Ruby Collections Build a Grocery List Program Build a Grocery List Program: Part 1

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

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 23,731 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>