I encountered a strange question about override initialize message of BigDecimal.
class Test1 < String
def initialize(a, b)
puts a
puts b
end
end
require 'bigdecimal'
class Test2 < BigDecimal
def initialize(a, b)
puts a
puts b
end
end
>> Test1.new('a', 'b')
a
b
>> Test2.new('a', 'b')
TypeError: wrong argument type String (expected Fixnum)
from (irb):17:in `new'
from (irb):17
Why I can override the initialize message of String, but not of BigDecimal?
When you look into sources of Ruby classes, you’ll see that the
Stringclass defines methodString#initialize, which is called afterString#new(inherited fromObject) for allocating a new instance. You don’t callString#initialize(or#super) in your new instance so you got""when you inspect the newly created object.BigDecimaldefines methodBigdecimal#new, which allocates its own object. Object creation consists of two parts – allocating space for new object and initializing it. You only defined initializing new object, so you stay with default allocating space for object. If you want to override it, you should define#newin your new class and callBigDecimal‘s#newwith proper arguments.Hope that clarifies a little what happen in your example.