【发布时间】:2011-11-26 15:16:18
【问题描述】:
我正在阅读的红宝石书让我有些困惑。如果我执行以下操作,我完全理解代码为什么会抛出错误;
class Person
def show_name
puts @name
end
end
person = Person.new
person.show_name
Person.show_name #(note the capital P) this line falls over
它会抛出一个错误,指出 Person 类没有名为 show_name 的方法,因为它是一个实例方法。我完全理解这一点。本书随后抛出了这个例子;
class Class
def add_accessor(accessor_name)
self.class_eval %Q{attr_accessor :#{accessor_name}}
end
end
class Person
end
person = Person.new
Person.add_accessor :name #note the capital P
Person.add_accessor :age #capital P here too
person.name = "Mikey"
person.age = 30
puts person.name
并继续说明您可以动态地将方法添加到类中是多么酷。我不明白的是,当方法本身没有这样定义时,为什么突然允许我将“add_accessor”方法称为类方法(大写P)?我以为所有的类方法都必须这样声明?
class Math
def self.PI
3.141
end
end
puts Math.PI
有没有大神赐教?
【问题讨论】: