我创建了以下课程
class BankAccount
def accountNumber
@accountNumber=5
end
def accountNumber=(value)
@accountNumber=value
end
end
我这样使用它:
account=BankAccount.new
=> #<BankAccount:0x0000000295d6c8>
account.accountNumber
=> 5
account.accountNumber="223"
=> 223
account.accountNumber
=> 5
为什么即使将accountNumber
设置为5
也等于223
?
答案 0 :(得分:4)
调用account.accountNumber
时,它会调用accountNumber
方法,您将其定义为:
def accountNumber
@accountNumber=5
end
有几种解决方法,一个简单的方法是:
class BankAccount
attr_accessor :account_number
def initialize(account_number=5)
@account_number = account_number
end
end
哪个作品很棒:
irb(main):009:0> x = BankAccount.new
=> #<BankAccount:0x00007fae449c5fc8 @account_number=5>
irb(main):010:0> x.account_number = 10
=> 10
irb(main):011:0> y = BankAccount.new
=> #<BankAccount:0x00007fae4495fed0 @account_number=5>
irb(main):012:0> y.account_number
=> 5
irb(main):013:0> z = BankAccount.new
=> #<BankAccount:0x00007fae480066a0 @account_number=5>
irb(main):015:0> z.account_number = 15
=> 15
irb(main):016:0> z.account_number
=> 15
Here是SO attr_accessor
工作原理的答案。
答案 1 :(得分:2)
由于您的方法,每次致电account.accountNumber
时,您都将@accountNumber
分配为5
。
要避免这种情况,您可以这样做:
class BankAccount
DEFAULT_NUMBER = 5
DEFAULT_AMOUNT = 10
attr_accessor :number, :amount
def initialize
set_default_values
end
def set_default_values
@number = DEFAULT_NUMBER
@amount = DEFAULT_AMOUNT
end
end
现在您可以根据需要分配值
account = BankAccount.new # => #<BankAccount:0x000055d581adbd38 @number=5 @amount=10>
account.number = 500
account.number # => 500
account.amount = 20
account.amount # => 20
account.amount = BankAccount::DEFAULT_AMOUNT
account.amount # => 10
account.set_default_values
account # => #<BankAccount:0x000055d581adbd38 @number=5 @amount=10>