【发布时间】:2014-04-14 07:36:23
【问题描述】:
作为一个以前只接触过有限的编程并且主要是 Python 和 C++ 的人,我发现 Ruby 是一种非常令人耳目一新且令人愉快的语言,但是我在理解 Ruby 对类构造函数和虚拟访问器的使用方面有点困难,特别是什么是构造函数,什么不被认为是构造函数,以及我是否正确理解了虚拟访问器。
这是一个示例(归功于 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}"
感谢所有帮助我理解这段代码。
【问题讨论】:
标签: ruby oop constructor accessor