How do I define the class name method as Integer () and when should I use it?

advertisements

Some classes like Integer able to create a instance by

Integer(1) #=> 1

It seems the class name works as method name. How can I create a method like this and when should I use it instead of define a initialize method?


Integer is a Kernel method. In fact, it is defined as Kernel.Integer.

You can simply create a new method that acts as initializer for your custom class:

class Foo
  def initialize(arg)
    @arg = arg
  end
end

def Foo(arg)
  Foo.new(arg)
end

Foo("hello")
# => #<Foo:0x007fa7140a0e20 @arg="hello">

However, you should avoid to pollute the main namespace with such methods. Integer (and a few others) exists because the Integer class has no initializer.

Integer.new(1)
# => NoMethodError: undefined method `new' for Integer:Class

Integer can be considered a factory method: it attempts to convert the input into an Integer, and returns the most appropriate concrete class:

Integer(1).class
# => Fixnum
Integer(1000 ** 1000).class
# => Bignum

Unless you have a real reason to create a similar initializer, I'd just avoid it. You can easily create static methods attached to your class that converts the input into an instance.