ironsand ironsand - 8 months ago 29
Ruby Question

How to define class name method like Integer() and when should I use it?

Some classes like

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


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

def Foo(arg)

# => #<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.
# => 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:

# => 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.