gpt4 book ai didi

ruby - 什么是 "Class.new"?

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

我不明白下面这段代码中的Sheep = Class.new部分。

module Fence 
Sheep = Class.new do
def speak
"Bah."
end
end
end

def call_sheep
Fence::Sheep.new.speak
end

它到底在做什么?

最佳答案

根据文档,Class.new

Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given).

此外,

You can give a class a name by assigning the class object to a constant.

Sheep 是常量,因此您的代码等同于:

module Fence 
class Sheep
def speak
"Bah."
end
end
end

关于ruby - 什么是 "Class.new"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31531521/

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