mardi 2 juillet 2019

Turning an array into a hash, then, adding a key => value and increment when key is present

I think this will require an if statement, here are the tests this method will go through:

  describe "#consolidate_cart" do
    it "adds a count of one to each item when there are no duplicates" do
      cart = [find_item('TEMPEH'), find_item('PEANUTBUTTER'), find_item('ALMONDS')]
      result = consolidate_cart(cart)
      result.each do |item, attributes|
        expect(attributes.keys).to include(:count)
        expect(attributes[:count]).to eq(1)
      end
    end

    it "increments count when there are multiple items" do
      avocado = find_item('AVOCADO')
      cart = [avocado, avocado, find_item('KALE')]

      result = consolidate_cart(cart)
      expect(result["AVOCADO"][:price]).to eq(3.00)
      expect(result["AVOCADO"][:clearance]).to eq(true)
      expect(result["AVOCADO"][:count]).to eq(2)

      expect(result["KALE"][:price]).to eq(3.00)
      expect(result["KALE"][:clearance]).to eq(false)
      expect(result["KALE"][:count]).to eq(1)
    end
  end

Here is what I have done so far:

def consolidate_cart(cart)
  newCart = Hash[cart]
  if newCart[:count] == 1;
    newCart[:count] += 1;
  else 
    newCart
 end
end

I am getting the following error:

  1) Grocer #consolidate_cart increments count when there are multiple items
     Failure/Error: expect(result["AVOCADO"][:price]).to eq(3.00)

     NoMethodError:
       undefined method `[]' for nil:NilClass
     # ./spec/grocer_spec.rb:40:in `block (3 levels) in <top (required)>'

It is passing the first test when there are no duplicates but failing the next...as always I appreciate any help/explanation.

Aucun commentaire:

Enregistrer un commentaire