某些类Integer
能够通过
Integer(1) #=> 1
似乎类名作为方法名称。
如何创建这样的方法以及何时应该使用它而不是定义initialize
方法?
答案 0 :(得分:3)
这不是一个类,它是一个以大写字母开头的方法(Kernel#Integer
)。
def Foo(x = 1)
"bar to the #{x}!"
end
Foo(10) #=> "bar to the 10!"
它也可以与同名的常量共存:
module Foo; end
Foo.new #=> #<Foo:0x007ffcdb5151f0>
Foo() #=> "bar to the 1!"
但是,一般来说,认为创建以大写字母开头的方法是一个坏主意并且令人困惑。
答案 1 :(得分:3)
Integer
是一种Kernel
方法。实际上,它被定义为Kernel.Integer
。
您只需创建一个新方法,作为自定义类的初始值设定项:
class Foo
def initialize(arg)
@arg = arg
end
end
def Foo(arg)
Foo.new(arg)
end
Foo("hello")
# => #<Foo:0x007fa7140a0e20 @arg="hello">
但是,您应该避免使用此类方法污染主命名空间。 Integer
(以及其他一些)存在,因为Integer
类没有初始化程序。
Integer.new(1)
# => NoMethodError: undefined method `new' for Integer:Class
Integer
可以被视为工厂方法:它尝试将输入转换为Integer,并返回最合适的具体类:
Integer(1).class
# => Fixnum
Integer(1000 ** 1000).class
# => Bignum
除非你有真正的理由来创建类似的初始化程序,否则我只是避免使用它。您可以轻松创建附加到类的静态方法,将输入转换为实例。