【发布时间】:2011-11-26 06:26:24
【问题描述】:
我不确定这之间的区别。
def String.hello
puts "hello there"
end
和
x = Person.new
def x.hello
puts "hello there"
end
据我了解,第二个代码块将创建一个 Person 类的对象。当我执行 def x.hello 时,它会创建一个匿名类(单例类),在向 x 对象发送消息时首先检查方法。
def String.hello 的情况是否相同? String 只是类 Class 的一个实例,对吗?我已经读过,执行 def String.hello 会将方法添加为 String 的类方法之一......这与创建的匿名类不同,该类位于对象及其类之间它得到它的实例方法。
上面的两个代码块会发生什么?
【问题讨论】: