Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Calling setters from within an object [duplicate]

Tags:

ruby

I've been working through the Pragmatic Programmers 'Programming Ruby' book and was wondering if it was possible to call a setter method within a class rather than just assigning to the instance variable directly.

class BookInStock

  attr_reader :isbn, :price

  def initialize (isbn, price)
    @isbn = isbn
    @price = Float(price)
  end

  def price_in_cents
    Integer(price*100 + 0.5)
  end

  def price_in_cents=(cents)
    @price = cents/100.0
  end

  def price=(dollars)
    price = dollars if dollars > 0
  end

end

In this case I am using a setter to ensure that the price can't be negative. What i want to know is if it is possible to call the price setter from within the price_in_cents setter so that I wont have to write extra code to ensure that the price will be positive.

Thanks in advance

like image 671
Dave Carpenter Avatar asked Dec 05 '12 02:12

Dave Carpenter


1 Answers

Use self.setter, ie:

def price_in_cents=(cents)
    self.price = cents/100.0
end
like image 53
David Miani Avatar answered Oct 17 '22 07:10

David Miani