2016-08-09 47 views
1

Ich würde mich freuen, wenn mir jemand helfen kann herauszufinden, warum mein Code nicht weitergegeben wird. Ich habe hier Argumente gegeben.Verschachtelte Hash-Manipulation

Warenkorb Artikel:

{ 
    "AVOCADO" => {:price => 3.0, :clearance => true, :count => 3}, 
    "KALE" => {:price => 3.0, :clearance => false, :count => 1} 
} 

Coupons:

{:item => "AVOCADO", :num => 2, :cost => 5.0} 

Es erfordert mich dies zurück:

{ 
    "AVOCADO" => {:price => 3.0, :clearance => true, :count => 1}, 
    "KALE" => {:price => 3.0, :clearance => false, :count => 1}, 
    "AVOCADO W/COUPON" => {:price => 5.0, :clearance => true, :count => 1}, 
    } 

Hier ist mein Code:

def apply_coupons(cart:[], coupons:[]) 

    app_coupon = {} 
    cart.each do |items| 
    items.each do |item_name, value| 
     app_coupon[item_name] = value 
     coupons.each do |coupon| 
     if coupon[:item] == item_name 
      app_coupon["#{coupon[:item]} W/COUPON"] = {:price => coupon[:cost], :clearance => value[:clearance], :count => value[:count]/coupon[:num] } 
      app_coupon[item_name][:count] -= coupon[:num] 
     end 
     end 
    end 
    end 
    app_coupon 
end 
+0

Es ist nicht klar, warum dein Coupon 'num: 2' hat und du nur einen mit einem Coupon diskontiert hast. Sie deklarieren auch Schlüsselwortargumente mit Array-Standardwerten, wenn Sie tatsächlich einen Hash erwarten. – tadman

+0

Ja, meine Argumente sind Hashes innerhalb des Cart & Coupons Array. –

+0

Vielleicht möchten Sie die Methode als 'cart: {}, Coupons: {}' deklarieren, wenn das der Fall ist. Es ist merkwürdig, dass Sie Ruby 2.3-Schlüsselworte verwenden, aber Ruby 1.8-Hash-Notation. Für Konsistenz: 'Preis: 3.0, Abstand: wahr, ...' – tadman

Antwort

0

Ein mögliches Problem ..

Coupons:

{:item => "AVOCADO", :num => 2, :cost => 5.0} 

... dies ist nur ein einziger Hash, aber in Ihrem Code Sie tun ...

coupons.each do |coupon| 

.. Sie erwarten also ein Array. Du solltest Coupons machen:

[{:item => "AVOCADO", :num => 2, :cost => 5.0}] 
+0

Eigentlich sieht es so aus, wenn ich es in irb versuche. 'apply_coupons (Einkaufswagen: [{ " AVOCADO "=> {: Preis => 3.0,: Abstand => Wahr,: Anzahl => 3}, " KALE "=> {: Preis => 3.0,: Abstand = > false,: count => 1} }], Gutscheine: [{: item => "AVOCADO",: num => 2,: kosten => 5.0}]) ' –

+0

Also habe ich es ausprobiert, es funktioniert gut! Ich habe das Ergebnis ... '{" AVOCADO "=> {: price => 3.0,: Abstand => wahr,: Anzahl => 1}," AVOCADO W/COUPON "=> {: price => 5.0,: clearance => true,: count => 1}, "KALE" => {: price => 3.0,: clearance => falsch,: count => 1}} ' – SteveTurczyn

+0

Also das Problem ist dein Test (rspec). Kannst du deinen RSPC-Code posten und erklären, welchen Fehler du in deinen Tests siehst? – SteveTurczyn