我如何制作一个 class 的构造函数看起来像内置 class 的构造函数?
How do I make a class whose constructor looks like the constructor of a built-in class?
Complex
是内置的 class。为了制作一个 Complex
对象,我写:
Complex(10, 5)
但是如果我自己创建 class Thing
:
class Thing
def initalize()
end
end
创建一个新的Thing
,我必须写:
Thing.new(...)
是否可以为 Thing
创建一个构造函数,这样我就可以写:
Thing(...)
让它像内置的 class 一样工作,例如 Complex(1,1)
?
class Dog
def initialize(name)
@name = name
end
def greet
puts 'hello'
end
end
def Dog(x)
Dog.new(x) #Create a new instance of the Dog class and return it.
end
d = Dog("Rover")
d.greet
--output:--
hello
Complex
可以引用内核中定义的Complex
class, or to the Complex
method:
Object.const_get(:Complex) #=> Complex
Object.method(:Complex) #=> #<Method: Class(Kernel)#Complex>
后者称为全局方法(或全局函数)。 Ruby 将 Kernel
中的这些方法定义为私有实例方法:
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
Complex
是内置的 class。为了制作一个 Complex
对象,我写:
Complex(10, 5)
但是如果我自己创建 class Thing
:
class Thing
def initalize()
end
end
创建一个新的Thing
,我必须写:
Thing.new(...)
是否可以为 Thing
创建一个构造函数,这样我就可以写:
Thing(...)
让它像内置的 class 一样工作,例如 Complex(1,1)
?
class Dog
def initialize(name)
@name = name
end
def greet
puts 'hello'
end
end
def Dog(x)
Dog.new(x) #Create a new instance of the Dog class and return it.
end
d = Dog("Rover")
d.greet
--output:--
hello
Complex
可以引用内核中定义的Complex
class, or to the Complex
method:
Object.const_get(:Complex) #=> Complex
Object.method(:Complex) #=> #<Method: Class(Kernel)#Complex>
后者称为全局方法(或全局函数)。 Ruby 将 Kernel
中的这些方法定义为私有实例方法:
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