Is there a reasonable replacement for ‘?’ below?
class Super
def initialize
sub = '?' # something that yields obj.class
puts "Created for subclass #{sub}"
end
end
class Sub < Super
end
obj = Sub.new
Thanks,
Sab
Is there a reasonable replacement for ‘?’ below?
class Super
def initialize
sub = '?' # something that yields obj.class
puts "Created for subclass #{sub}"
end
end
class Sub < Super
end
obj = Sub.new
Thanks,
Sab
“Szabolcs Szasz” sz@szasz.hu writes:
Is there a reasonable replacement for ‘?’ below?
class Super def initialize sub = '?' # something that yields obj.class puts "Created for subclass #{sub}" end end
‘type’ returns the class of its receiver, so:
class Super
def initialize
sub = type
puts “Created for subclass #{sub}”
end
end
class Sub < Super
end
obj = Super.new #=> Created for subclass Super
obj = Sub.new #=> Created for subclass Sub
So can also use #class, but you have to be careful to call it with an
explicit receiver, or Ruby will think you’re starting a class
definition.
Cheers
Dave
I did start with the class/type method, but still only saw the
superclass in the constructor… Strange, I must have missed
something subtle in the actual code (which is different from
my gutted example below).
Needless to say, now it does work just fine in the original
code, too…
Well, it can be a bit frustrating to be a newbie sometimes…
Thanks very much,
Sab
----- Original Message -----
From: “Dave Thomas” Dave@PragmaticProgrammer.com
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Sunday, October 20, 2002 4:07 AM
Subject: Re: Is subclass known in superclass.initialize? (virtual constructor theme…)
“Szabolcs Szasz” sz@szasz.hu writes:
Is there a reasonable replacement for ‘?’ below?
class Super def initialize sub = '?' # something that yields obj.class puts "Created for subclass #{sub}" end end
‘type’ returns the class of its receiver, so:
class Super
def initialize
sub = type
puts “Created for subclass #{sub}”
end
endclass Sub < Super
endobj = Super.new #=> Created for subclass Super
obj = Sub.new #=> Created for subclass SubSo can also use #class, but you have to be careful to call it with an
explicit receiver, or Ruby will think you’re starting a class
definition.Cheers
Dave
‘type’ returns the class of its receiver, so:
(snip)
So can also use #class, but you have to be careful to call it with an
explicit receiver, or Ruby will think you’re starting a class
definition.
Object#type is being deprecated in the development version (though I
don’t know why), so I’d recommend “self.class”.
At Sun, 20 Oct 2002 11:07:51 +0900, Dave Thomas wrote:
–
/
/__ __ Akinori.org / MUSHA.org
/ ) ) ) ) / FreeBSD.org / Ruby-lang.org
Akinori MUSHA aka / (_ / ( (__( @ iDaemons.org / and.or.jp
“When I leave I don’t know what I’m hoping to find
When I leave I don’t know what I’m leaving behind…”