ironsand
ironsand

Reputation: 15151

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

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?

Upvotes: 2

Views: 258

Answers (2)

Simone Carletti
Simone Carletti

Reputation: 176382

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.

Upvotes: 3

Andrew Marshall
Andrew Marshall

Reputation: 96934

It’s not a class, it’s a method (Kernel#Integer) that begins with a capital letter.

def Foo(x = 1)
  "bar to the #{x}!"
end

Foo(10)  #=> "bar to the 10!"

It can co-exist with a constant of the same name as well:

module Foo; end

Foo.new  #=> #<Foo:0x007ffcdb5151f0>
Foo()    #=> "bar to the 1!"

Generally, though, it’s thought that creating methods that begin with a capital letter is a bad idea and confusing.

Upvotes: 3

Related Questions