gpt4 book ai didi

Ruby 2.3.3 The Well Grounded Rubyist - 未定义方法 `balance' for 25 :Fixnum

转载 作者:行者123 更新时间:2023-12-04 10:55:26 25 4
gpt4 key购买 nike

我目前正在阅读“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 session 中使用过这个,就像这样
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。

最佳答案

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

And why FIXNUM is getting involved. I thought @balance would be an INTEGER.



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

Ruby 2.4 将它们替换为 unified Integer class .

关于Ruby 2.3.3 The Well Grounded Rubyist - 未定义方法 `balance' for 25 :Fixnum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59235910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com