2014-09-21 107 views
0

由於在註釋行下面的代碼與out「amount = 0」做同樣的事情,參數「amount」被定義爲0的區別是什麼?參數「數量」和「數量= 0」之間的區別?

class Account 
    attr_accessor :balance 
    def initialize(amount=0) 
     self.balance = amount 
    end 
    def +(x) 
     self.balance += x 
    end 
    def -(x) 
     self.balance -= x 
    end 
    def to_s 
     balance.to_s 
    end 
end 

acc = Account.new(20) 
acc -= 5 
puts acc 

class Account 
    attr_accessor :balance 
    def initialize(amount) 
     self.balance = amount 
    end 
    def +(x) 
     self.balance += x 
    end 
    def -(x) 
     self.balance -= x 
    end 
    def to_s 
     balance.to_s 
    end 
end 

acc = Account.new(20) 
acc -= 5 
puts acc 

我是個初學者。謝謝你的幫助!

回答

1

在參數列表中指定amount = 0使參數amount成爲可選參數(其中0作爲其默認值)。

如果您未指定amount參數,則它將爲0

account = Account.new # without amount argument 
account.balance # => 0 

account = Account.new 10 # with amount argument 
account.balance # => 10 
+0

哦...我忘了。是啊。謝謝! – 2014-09-21 14:37:09

+0

@ C.Graco,歡迎來到Stack Overflow!有些人試圖回答你的問題。如果這對你有幫助,你可以通過[接受答案](http://meta.stackoverflow.com/a/5235)告訴社區,這對你最有用。 – falsetru 2014-09-21 14:37:47

0

唯一的區別是:

第一類設置的默認值

 

    class Account 
     attr_accessor :balance 
     def initialize(amount=0) 
      self.balance = amount 
     end 
     ... class omitted 

    end 

    account = Account.new 
    account.balance # should be equal to 0 

 

     class Account 
     attr_accessor :balance 
     def initialize(amount) 
      self.balance = amount 
     end 
     ... class omitted 

     end 

     account = Account.new nil 
     account.balance # should be equal to nil 

相關問題