I've been stuck on this for quite a while now. Take a look at this:
class SuperClass
def self.new(*args, **kwargs, &block)
i = allocate()
# Extra instance setup code here
i.send(:initialize, *args, **kwargs, &block)
return i
end
end
class Test < SuperClass
def initialize
puts "No args here"
end
end
The class SuperClass
basically "reimplements" the default new
method so that some extra initialization can happen before initialize
.
Now, the following works just fine:
t = Test.allocate
t.send(:initialize, *[], **{}, &nil)
However, this does not:
t = Test.new
ArgumentError: wrong number of arguments (1 for 0) from (pry):7:in `initialize'
It fails on this line in SuperClass
:
i.send(:initialize, *args, **kwargs, &block)
But apparently it only fails if called within the new
method. I have confirmed that args == []
, kwargs == {}
and block == nil
.
Is anybody able to explain this?
Ruby version:
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]
Please refrain from suggesting that I don't overload Class.new
. I am aware I can use Class.inherited
and Class.append
for the same result. This question is only about why the call to initialize
fails.