samedi 23 mai 2015

Ruby: When to use self and when not to?

I understand what Ruby self means, and I was trying to solve certain challenges on Tealeaf: http://ift.tt/1F7DhEe

Here is the actual problem:

Snippet 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

Now for Snippet 1, running this code:

bank_account = BankAccount.new(3000)
puts bank_account.positive_balance?

prints true on the console, whereas for snippet 2:



Snippet 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

Now for snippet 2, on running this code:

ie = InvoiceEntry.new('Water Bottle', 2)
ie.update_quantity(20)
puts ie.quantity #> returns 2

Why is this not updating the value? Why is it working for the first case while not for the second?

Aucun commentaire:

Enregistrer un commentaire