class Player
include Playable
attr_reader :points
attr_accessor :health, :name
def initialize(name, health=100, points=0)
@name = name.capitalize
@health = health
@found_treasures = Hash.new(0)
@points = points
end
end
module Playable
def blam
self.health -= 10
puts "#{name} just got blammed yo."
end
def w00t
self.health += 15
puts "\n#{name} just got w00ted."
end
def score
self.health + points
end
def strong?
health > 100
end
end
所以在上面的代码中的实例方法中,我明白的是,为了设置属性的健康,它需要1)是在类的存取方法,我包括模块in和2)它需要模块中的自我。红宝石自我在模块
在这种情况下,自我指的是什么?由于模块中的方法是实例方法,因此需要在对象上调用它们,所以self指向Player类的实例?如果这是正确的,那么self.health指的是一个attr_accessor方法,这段代码很有意义。没有“自我”这个词,它会是一个局部变量赋值是否正确?这是什么?
不,“健康”和“self.health”一样是对访问者的调用。尽管如此,“self.health”更加明确和可读。 – Amadan 2014-11-25 06:48:21