【发布时间】:2015-05-23 10:47:17
【问题描述】:
我了解 Ruby self 的含义,我正在尝试解决 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
现在对于 Snippet 1,运行以下代码:
bank_account = BankAccount.new(3000)
puts bank_account.positive_balance?
在控制台上打印 true,而对于 sn-p 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
现在对于 sn-p 2,运行此代码:
ie = InvoiceEntry.new('Water Bottle', 2)
ie.update_quantity(20)
puts ie.quantity #> returns 2
为什么这不更新值? 为什么它适用于第一种情况而不适用于第二种情况?
【问题讨论】:
-
在
update_quantity中,您错误地分配给quantity(局部变量)而不是@quantity(实例变量)。 -
看看这个,尤其是关于隐含性的部分:stackoverflow.com/a/17709189/276959
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-2.0