Question

As someone who previously had only a limited exposure to programming and this was mainly in Python and C++, I find Ruby to be really refreshing and enjoyable language, however I am having a little trouble understanding Ruby's use of class constructors and virtual accessors, specifically with what is and what is not considered to be a constructor and whether I understand virtual accessors correctly.

Here's an example (credit is due to the Pragmatic Bookshelf, Programming Ruby 1.9 & 2.0):

class BookInStock
  attr_accessor :isbn, :price # is this part of the class constructor?

  def initialize(isbn, price) # and is the initialize method part of a constructor or just a regular method?
    @isbn = isbn 
    @price = price
  end

  def price_in_cents 
    Integer(price*100+0.5)
  end

  def price_in_cents=(cents) # this is a 'virtual accessor' method, trough which I am able to update the price down the road...?
    @price = cents / 100.0 
  end
end

book = BookInStock.new('isbn1', 23.50)
puts "Price: #{book.price}"
puts "Price in cents: #{book.price_in_cents}"
book.price_in_cents = 1234 # here I am updating the value thanks to the 'virtual accessor' declared earlier, as I understand it
puts "New price: #{book.price}"
puts "New price in cents: #{book.price_in_cents}"

Thanks for all the help I could get understanding this piece of code.

Was it helpful?

Solution

1 attr_accessor :isbn, :price # is this part of the class constructor?

This line is to keep concept of access private member through method only philosophy. It's in effect equivalent to declare two private members and their getter and setter methods, has nothing to do with constructor.

2 def initialize(isbn, price) # and is the initialize method part of a constructor or just a regular method?

To put it in the easy way, this is THE constructor. The method get called upon 'new' keyword

3 def price_in_cents=(cents) # this is a 'virtual accessor' method, trough which I am able to update the price down the road...?

It's just an alternative of price= method, which takes argument in different format, the price= method is the setter method automatically generated by your question line 1.

4 book.price_in_cents = 1234 # here I am updating the value thanks to the 'virtual accessor' declared earlier, as I understand it

Keep in mind this feels like assigning a variable but really is accessing a setter method, in consistent with the concept reflected in your question line 1 and 3.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top