DEV Community

loading...

Green Grocer Lab

2spacemilk profile image Mark Harless Updated on ・2 min read

Problem

I have a shopping cart full of items that I need to consolidate with a consolidate_cart method. This cart is made up of one array and needs to be put into a hash. Each index item has a name, price, if it's on clearance and how many of each item there are (count).

For example, this:

[
  {"AVOCADO" => {:price => 3.00, :clearance => true }},
  {"AVOCADO" => {:price => 3.00, :clearance => true }},
  {"KALE"    => {:price => 3.00, :clearance => false}}
]
Enter fullscreen mode Exit fullscreen mode

Needs to turn into this:

{
  "AVOCADO" => {:price => 3.00, :clearance => true, :count => 2},
  "KALE"    => {:price => 3.00, :clearance => false, :count => 1}
}
Enter fullscreen mode Exit fullscreen mode

What I Learned

This was a particularly difficult challenge for me and I needed help because I didn't even know where to start. I wasn't terribly far off, though. I got a more firm understanding of .each and what the |pipes| mean as well as, obviously, moving nested hashes in an array to a single hash.

While asking for help I was told to install Pry which is a Ruby program that lets you stop your code at a specific line to better debug it. I didn't get to play with it on my own but it does seem like a very useful tool for a Ruby programmer.

Final Iteration

def consolidate_cart(cart)
  output = {}
  cart.each do |item|
    item_name = item.keys[0]
    if output[item_name]
      output[item_name][:count] += 1 
    else
      output[item_name] = item[item_name]
      output[item_name][:count] = 1 
    end
  end
  output
end
Enter fullscreen mode Exit fullscreen mode

Original Problem

The cart starts as an array of individual items. Translate it into a Hash that includes the counts for each item with the consolidate_cart method.

For instance, if the method is given the array below:

[
  {"AVOCADO" => {:price => 3.00, :clearance => true }},
  {"AVOCADO" => {:price => 3.00, :clearance => true }},
  {"KALE"    => {:price => 3.00, :clearance => false}}
]
Enter fullscreen mode Exit fullscreen mode

then the method should return the hash below:

{
  "AVOCADO" => {:price => 3.00, :clearance => true, :count => 2},
  "KALE"    => {:price => 3.00, :clearance => false, :count => 1}
}
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide