class Dia < Date
def initialize(ano, mes, dia, obj_mes) @mes = obj_mes
super(ano, mes, dia)
end
end
a = Dia.new
=> #<Dia: -4712-01-01 ((0j,0s,0n),+0s,2299161j)> #Was expecting an error, no arguments has been passed
a = Dia.new(2012, 6, 21, "foo")
=> TypeError: no implicit conversion to float from string
from (irb):31:in `new'
from (irb):31
from C:/Ruby193/bin/irb:12:in `<main>' #Seems that the 4th argument is taked by...super too?? WTF
a = Dia.new(2012, 5, 26)
=> #<Dia: 2012-05-26 ((2456074j,0s,0n),+0s,2299161j)>
a = Dia.new(2012, 5, 26, Date::ITALY)
=> #<Dia: 2012-05-26 ((2456074j,0s,0n),+0s,2299161j)> #Obvious is taked by super...but why? I don't expect that
We can see that new() doesn't matter if it is no receive parameters, or
if it receive, it behave like make Date.new, but why? I'm re-defining
the method initialize in Dia, it sholud(am I wrong?) take exactly 4
parameters and asign the last one to the instance variable @mes. Why is
this happening? I've tried putting super in the first line of the
definition but the same's returned. Thanks for your time.
class Dia < Date
def initialize
#@mes = obj_mes #super(ano, mes, dia)
puts 'init'
end
end
Dia.new
--output:--
<nothing>
So that means Dia#initialize is not being called by Dia.new, which is a
bit confounding. Apparently, the date module does some complex aliasing
which causes Class.new (which Dia inherits) not to call initialize().
Your subclassing of Date problem was discussed in 2001, by none other
than Matz, and supposedly that behavior was going to be fixed:
Well, the class Dia(It's day in spanish) represent a day. Each instance
of this class have like 10 inst. variables. I wanted to subclass Date
because I want to be available +() or -() or cweek() to a Dia instance,
in the way that it behave like a Date object does.
You can use composition instead of subclassing, as in
require 'date'
class Dia
def initialize(ano, mes, dia, obj_mes)
@mes=obj_mes @d = Date.new(ano,mes,dia)
end
def print()
printf "date = %04d-%02d-%02d : obj_mes = %-s\n ", @d.year, @d.month, @d.day, @mes
end
end
Then better use composition as has been suggested. Inheriting core
classes is rarely a good idea. What you have is actually something
else which happens to have a data attached to it as well. If you need
numeric operations one of my blog articles might help you to implement
operators properly:
On Thu, Sep 27, 2012 at 2:30 PM, Damián M. González <lists@ruby-forum.com> wrote:
Why are you subclassing Date in the first place?
Well, the class Dia(It's day in spanish) represent a day. Each instance
of this class have like 10 inst. variables. I wanted to subclass Date
because I want to be available +() or -() or cweek() to a Dia instance,
in the way that it behave like a Date object does.