2

我目前正在阅读“The Well Grounded Rubyist 2nd Edition”,我在第 196 页,并获得了以下代码

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

我在和 irb 会话中使用过这个,就像这样

2.3.3 :001 > require './account.rb'
 => true
2.3.3 :002 > acc = Account.new(20)
 => #<Account:0x007fccb1834ef8 @balance=20>
2.3.3 :003 > balance
NameError: undefined local variable or method `balance' for main:Object
    from (irb):3
    from /Users/BartJudge/.rvm/rubies/ruby-2.3.3/bin/irb:11:in `<main>'
2.3.3 :004 > acc.balance
 => 20
2.3.3 :005 > acc+=5
 => 25
2.3.3 :006 > acc.balance
NoMethodError: undefined method `balance' for 25:Fixnum
    from (irb):6
    from /Users/BartJudge/.rvm/rubies/ruby-2.3.3/bin/irb:11:in `<main>'
2.3.3 :007 > acc -= 5
 => 20
2.3.3 :008 > acc.balance
NoMethodError: undefined method `balance' for 20:Fixnum
    from (irb):8
    from /Users/BartJudge/.rvm/rubies/ruby-2.3.3/bin/irb:11:in `<main>'
2.3.3 :009 >

第 4 行按我预期的方式工作acc.balance 但是,当我在第 8 行再次使用它时,出现以下错误undefined method `balance' for 20:Fixnum

当我执行以下操作时,它会按照我的预期始终如一地工作。

 => true
2.3.3 :002 > acc = Account.new(20)
 => #<Account:0x007f82d1834f18 @balance=20>
2.3.3 :003 > acc.balance
 => 20
2.3.3 :004 > acc.balance
 => 20
2.3.3 :005 > acc.+ (5)
 => 25
2.3.3 :006 > acc.balance
 => 25
2.3.3 :007 > acc.-(10)
 => 15
2.3.3 :008 > acc.balance
 => 15
2.3.3 :009 >

我假设这与方法的调用方式有关,但我找不到任何解释。是否有人能够阐明结果的差异,以及为什么 FIXNUM 参与其中。我认为@balance 将是一个整数。

TIA。

4

2 回答 2

1

和赋值运算+=-=实际上是重新分配变量。acc += 1实际上只是acc = acc + 1.

以及为何 FIXNUM 参与其中。我认为@balance 将是一个整数。

在 Ruby 2.4 之前,有两个类——Fixnum 和 Bignum,它们代表不同大小的整数。

Ruby 2.4 用统一的 Integer 类取代了它们。

于 2019-12-08T14:38:02.453 回答
1

balance单独调用会引发NameError,因为它试图调用 main 上尚未定义的对象。如果你只是调用像fooor这样的随机词,你会得到同样的错误bar。必须在对象上调用方法。

Max 的回答解释了部分问题。但是,我建议您像这样定义您的类以避免该错误。

class Account
  attr_accessor :balance

  def initialize(amount=0)
    @balance = amount
  end

  def add(x)
    @balance += x
  end

  def subtract(x)
    @balance -= x
  end

  def to_s
    @balance.to_s
  end

end
于 2019-12-08T14:44:57.770 回答