gpt4 book ai didi

ruby - 如何创建一个类,其构造函数看起来像内置类的构造函数?

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

Complex 是一个内置类。为了创建一个 Complex 对象,我写了:

Complex(10, 5)

但是如果我创建自己的类Thing:

class Thing
def initalize()
end
end

要创建一个新的 Thing,我必须写:

Thing.new(...)

是否可以为 Thing 创建一个构造函数,这样我就可以写:

Thing(...)

让它像 Complex(1,1) 这样的内置类一样工作吗?

最佳答案

Complex 可以引用 Complex class ,或到 Complex method在内核中定义:

Object.const_get(:Complex) #=> Complex
Object.method(:Complex) #=> #<Method: Class(Kernel)#Complex>

后者称为全局方法(或全局函数)。 Ruby 在 Kernel 中定义了这些方法作为两者,私有(private)实例方法:

Kernel.private_instance_methods.grep /^[A-Z]/
#=> [:Integer, :Float, :String, :Array, :Hash, :Rational, :Complex]

和单例方法:

Kernel.singleton_methods.grep /^[A-Z]/
#=> [:Integer, :Float, :String, :Array, :Hash, :Rational, :Complex]

就像内核中的任何其他方法一样:

These methods are called without a receiver and thus can be called in functional form

您可以使用 module_function将您自己的全局方法添加到 Kernel:

class Thing
end

module Kernel
module_function

def Thing
Thing.new
end
end

Thing #=> Thing <- Thing class
Thing() #=> #<Thing:0x007f8af4a96ec0> <- Kernel#Thing
Kernel.Thing() #=> #<Thing:0x007fc111238280> <- Kernel::Thing

关于ruby - 如何创建一个类,其构造函数看起来像内置类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28845222/

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