How to create an object in Ruby without using new

Have this snippet:

def make_light_constructor(klass)
    eval("def #{klass}(*args) #{klass}.new(*args) end")
end

Now you can do this:

class Test
    make_light_constructor(Test)
    def initialize(x,y)
        print x + y
    end 
end

t = Test(5,3)

Yes, I know you're still defining a function outside a class - but it is only one function, and now any class you want can make use of its implementation rather than making one function per class.


c = Complex(1,2)

is actually calling a method on Kernel


Basically you can't - the () operator cannot be overriden in Ruby (Complex class is written in C).

You could achieve something similar using []:

class Bits
  def self.[](list)
    Bits.new list
  end
end

Which would allow something like:

b = Bits[[1,2]]