我不确定这之间的区别。
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 的类方法之一……这与创建的匿名类不同,该类位于对象与其获取实例方法的类之间。
上面的两个代码块会发生什么?