2011-11-15 1 views
0
class BookInStock  

    attr_reader :isbn 
    attr_accessor :price 

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

    def price_in_cents 
    Integer(price*100 + 0.5) # why can they use price here? why are they not using @price? 
    end 

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

book = BookInStock.new("isbn1", 33.80) 
puts "Price   = #{book.price}" 
puts "Price in cents = #{book.price_in_cents}" 
book.price_in_cents = 1234 
puts "Price   = #{book.price}" 
puts "Price in cents = #{book.price_in_cents}" 

答えて

4

attr_accessorはゲッターを作成するので。

あなたも、後でbook.priceを書くことができる理由です。しかし彼らの一部に矛盾の

種類、。

+0

ので、「無地」の価格は、getterメソッドはありますか? – lampShade

+1

はい。あなたは 'def price 'と書くことで同じことをすることができました。 @価格; end' –

+3

あなたのオブジェクトの中に 'price = 1'と書くべきではないことに注意してください。 '@price = 1'または' self.price = 1'のいずれかを行う必要があります。 –

関連する問題