Ruby 新手问题,关于 attr

tdxh20 · April 20, 2012 · Last by tdxh20 replied at April 20, 2012 · 2315 hits

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) 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}"

看这段代码,能跑的,但是 price 的值没有赋进去,我知道因为 price = cents / 100.0 没有 写@price,但是这行能运行的,我想知道这个 price 的值到底赋到哪去了 price 这个变量在 price_in_cents 里没有出现过,那怎么可以用的么

def price_in_cents=(cents) price = cents / 100.0 end 这个 price 被当成了局部变量,和你所定义的 price 不是一回事了 所以要指名, def price_in_cents=(cents) self.price = cents / 100.0 end 或者 def price_in_cents=(cents) @price = cents / 100.0 end 你直接用 price,Ruby 会首先当成赋值运算,而你希望的是调用 price 的方法。 attr_accessor 的作用只是定义一个语法糖衣,让你误以为他是属性,其实则不是。 attr_accessor:price 在 ruby 里面被叫做类宏,相当于两个方法定义: def price return @price end def price=(price) @price=price end 这两个方法调用的时候看上去就好像你给变量赋值一样。可惜,你想多了。 def price_in_cents Integer(price*100 + 0.5) end 这里的 price 由于没有这么一个变量,所以它就当成了调用方法,也就是 self.price,self 也就是你当前的对象。 明白了吧。

清楚明了,非常感谢

You need to Sign in before reply, if you don't have an account, please Sign up first.