如何创建一个类的构造函数看起来像一个内置类的构造函数? [英] How do I make a class whose constructor looks like the constructor of a built-in class?
本文介绍了如何创建一个类的构造函数看起来像一个内置类的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
复杂
是一个内置类。要创建复杂
对象,我写:
Complex
is a built-in class. To make a Complex
object, I write:
Complex(10, 5)
但是如果我创建自己的类 Thing
:
But if I create my own class Thing
:
class Thing
def initalize()
end
end
创建一个新的 Thing
Thing.new(...)
可以为 Thing
创建一个构造函数,所以我可以这样写:
Is it possible to create a constructor for Thing
so I can write:
Thing(...)
像 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
这篇关于如何创建一个类的构造函数看起来像一个内置类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文