8

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

Dave Carpenter
  • 197
  • 1
  • 5

1 Answers1

13

Use self.setter, ie:

def price_in_cents=(cents)
    self.price = cents/100.0
end
David Miani
  • 14,518
  • 2
  • 47
  • 66
  • 2
    why do you need self. with methods that are setters whereas you dont need to call self with other instance methods – Muhammad Umer Aug 13 '15 at 18:21
  • 4
    Because `foo = bar` is variable assignment, not a method call. There are other cases as well: `+ foo` is `foo.+@`, not `self + foo`, for example. – Jörg W Mittag Dec 29 '15 at 10:57