gpt4 book ai didi

Ruby 单例类

转载 作者:数据小太阳 更新时间:2023-10-29 07:47:03 25 4
gpt4 key购买 nike

我不确定这之间的区别。

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 的类方法之一....这与创建的匿名类不同,匿名类位于对象及其类之间它获取其实例方法。

上面的两个代码块发生了什么?

最佳答案

我喜欢 ruby 的这一部分。存在这种美丽的对称性,其中大部分核心功能只是高级功能的糖分,所以一旦您完全理解了一个概念,您就可以将这种理解应用到许多语言中。

Is this the same case for the def String.hello? String is just an instance of class Class correct?

是的,您正在创建 Class 的实例,并将其分配给常量。

I have read that doing def String.hello will add the method as one of String's class methods.... this would be different than an anonymous class being created that sits in between the object and its class where it gets its instance methods.

不,您缺少的部分是认为可以在不将其添加到单例类的情况下拥有类级别的方法。您拥有的是一个对象,它是 Class 的一个实例,并且您正在向位于它和 Class 之间的隐式类添加方法。有时你也会看到这种语法

class << self
def method
end
end

这是在做同样的事情,只是非常明确。

关于Ruby 单例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7573407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com