oop - Confused by Ruby's class constructors and virtual accessors -
as had limited exposure programming , in python , c++, find ruby refreshing , enjoyable language, having little trouble understanding ruby's use of class constructors , virtual accessors, , not considered constructor , whether understand virtual accessors correctly.
here's example (credit due pragmatic bookshelf, programming ruby 1.9 & 2.0):
class bookinstock attr_accessor :isbn, :price # part of class constructor? def initialize(isbn, price) # , initialize method part of constructor or regular method? @isbn = isbn @price = price end def price_in_cents integer(price*100+0.5) end def price_in_cents=(cents) # 'virtual accessor' method, trough able update price down 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 updating value 'virtual accessor' declared earlier, understand puts "new price: #{book.price}" puts "new price in cents: #{book.price_in_cents}" thanks understanding piece of code.
1 attr_accessor :isbn, :price # part of class constructor?
this line keep concept of access private member through method philosophy. it's in effect equivalent declare 2 private members , getter , setter methods, has nothing constructor.
2 def initialize(isbn, price) # , initialize method part of constructor or regular method?
to put in easy way, constructor. method called upon 'new' keyword
3 def price_in_cents=(cents) # 'virtual accessor' method, trough able update price down road...?
it's alternative of price= method, takes argument in different format, price= method setter method automatically generated question line 1.
4 book.price_in_cents = 1234 # here updating value 'virtual accessor' declared earlier, understand it
keep in mind feels assigning variable accessing setter method, in consistent concept reflected in question line 1 , 3.
Comments
Post a Comment