我目前正在阅读“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。