Ruby - 添加值并保存它们以继续对方法的下一次调用

时间:2014-10-27 04:46:08

标签: ruby

我有一个问题,当我在我的createGadget上调用时,当价格= 650且其他价格为32美元时,它不会加起来。当我打电话给它时,价格重置,价格现在是32。你怎么做才能保存以前的值(650)并加起来新值(32)?

def money_made(cash)
    temp = 0
    temp = cash + temp 
    return temp
end 

def createGadget(make, model, price, height, width, weight, weight_scale)
    a = Gadget.new( make, model, price, height, width, weight)
        @@reveune_earned += money_made(a.price) 
        print money_made(a.price)
        print "\n"

        @@no_of_products +=1 
        puts @@no_of_products 
    return a 
end 

编辑:

这是我忘记添加的测试人员:

c = AppleStore.new()
macbook= c.createGadget( :Apple, :Macbook, 650,  13, 10, 3, :pounds)
puts "here is your macbook"
puts macbook 
d = AppleStore.new()
miniIpod = c.createGadget( :Apple, :MinIPod, 32,  13, 10, 3, :pounds)

我想要的结果:

price is 683 dollars 

我得到的结果:

650 #price 
1  #counter 
here is your macbook
#<Gadget:0x23f1ed0>
32# now price is reset to 49 
2 #counter 

1 个答案:

答案 0 :(得分:0)

Using class variables to control state is a very bad idea. Printing stuff as side-effect from inside methods can be useful as a debugging technique, but you shouldn't leave those print calls in there. Also, I'm a little confused: why the class is called AppleStore if you need to pass the maker as an argument? What's the purpose of weight_scale if it's ignored inside the method? And what should the money_made method do?

If I may so, I'd refactor that code to something like this:

class Store
  def initialize(maker)
    @maker = maker
    @gadgets = []
  end

  def create_gadget(model, price, height, width, weight, weight_scale)
    gadget = Gadget.new(@make, model, price, height, width, weight, weight_scale)
    @gadgets << gadget
    gadget
  end

  def revenue
    @gadgets.reduce(0) { |total, gadget| total + gadget.price }
  end

  def number_of_gadgets
    @gadgets.count
  end
end

store = Store.new(:Apple)
macbook= store.create_gadget(:Macbook, 650,  13, 10, 3, :pounds)
puts "here is your macbook"
puts macbook
mini_ipod = store.create_gadget(:MinIPod, 32,  13, 10, 3, :pounds)
store.revenue
# => 682

store.number_of_gadgets
#=> 2