参数之间的差异"金额"和"金额= 0",在这种情况下?

时间:2014-09-21 10:51:09

标签: ruby

在此上下文中,对于在整个实例创建中定义为0的参数“amount”有什么区别,因为注释行下面的代码执行相同的操作而没有“amount = 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

我是初学者。谢谢你的帮助!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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