【问题标题】:Ruby: When to use self and when not to?Ruby:什么时候使用 self 什么时候不使用?
【发布时间】: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


【解决方案1】:

您正在将局部变量分配给quantity

如果您想分配给实例变量(通过您的def quantity= 函数),您需要这样做

self.quantity = updated_count if updated_count >= 0

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

在 sn-p 1 中,balance 是一个纯函数调用,因为没有进行赋值。

【讨论】:

  • 但是相应地,如果你在 Snippet 1 中看到, balance 也应该像一个局部变量,而 balance>=0 指的是方法并给出正确的答案
猜你喜欢
  • 2012-05-22
  • 1970-01-01
  • 2012-07-29
  • 2022-11-10
  • 1970-01-01
相关资源
最近更新 更多