我理解Ruby自我的意思,我试图解决一些挑战在Tealeaf: http://www.gotealeaf.com/books/oo_workbook/read/intermediate_quiz_1
下面是实际问题:片段1:
class BankAccount
def initialize(starting_balance)
@balance = starting_balance
end
# balance method can be replaced with attr_reader :balance
def balance
@balance
end
def positive_balance?
balance >= 0 #calls the balance getter instance level method (defined above)
end
end
现在对于代码片段1,运行以下代码:
bank_account = BankAccount.new(3000)
puts bank_account.positive_balance?
在控制台上输出true,而对于代码片段2:
片段2:
class InvoiceEntry
attr_reader :product_name
def initialize(product_name, number_purchased)
@quantity = number_purchased
@product_name = product_name
end
# these are attr_accessor :quantity methods
# quantity method can be replaced for attr_reader :quantity
def quantity
@quantity
end
# quantity=(q) method can be replaced for attr_writer :quantity
def quantity=(q)
@quantity = q
end
def update_quantity(updated_count)
# quantity=(q) method doesn't get called
quantity = updated_count if updated_count >= 0
end
end
现在对于代码片段2,运行这段代码:
ie = InvoiceEntry.new('Water Bottle', 2)
ie.update_quantity(20)
puts ie.quantity #> returns 2
为什么不更新值?为什么它对第一个案子有用而对第二个案子没用?
您正在将本地变量分配给quantity
。
如果您想分配给实例变量(通过您的def quantity=
函数),您需要执行
self.quantity = updated_count if updated_count >= 0
实际上,您正在对self
进行函数调用(quantity=
)。
在代码片段1中,balance
是一个纯函数调用,因为没有赋值。