Ruby:什么时候使用self而不是什么时候?

时间:2015-05-23 10:47:18

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-2.0

我理解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

现在,对于Snippet 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

为什么不更新这个值? 为什么它适用于第一种情况而不适用于第二种情况?

1 个答案:

答案 0 :(得分:3)

您正在为quantity分配本地变量。

如果要分配给实例变量(通过def quantity=功能),则需要执行

self.quantity = updated_count if updated_count >= 0

基本上,您正在quantity=上进行函数调用(self)。

在代码段1中,balance是纯函数调用,因为没有分配。

相关问题