ruby - Can I change an object's type inside its own methods? -



ruby - Can I change an object's type inside its own methods? -

it great if alter object's class within own methods like:

class dog < animal def initialize(color, size) #do stuff end def do_lots_of_stuff #really long involved calculations different classes , methods #and objects can't alter @ point if random_condition self = super_special_dog.new(@color, @size, specialness) end end end class super_special_dog < dog def initialize(color, size, specialness) #do stuff end end

is there way convert instance of dog, 'fido', super_special_dog after fido.do_lots_of_stuff called, fido.is_a? super_special_dog homecoming true , other methods/classes can operate on fido super_special_dog's methods , variables on?

i tried above construction , got error can't alter value of self (syntaxerror). can create super_special_dog based on dog or on animal doesn't matter needs.

i can see other questions converting object outside own methods need inside. have 2k-3k lines of code intertwined hard alter @ point.

first of all, no 1 should care whether fido dog or super_special_dog - should care tricks fido can (that is, methods responds to). that's duck-typing (dog-typing?) way things.

if remove requirement actual class needs changed, it's trivial add together new functionality instance within itself.

class dog def become_special @special = true extend specialtraits end end module specialtraits def do_special_thing end end fido = dog.new rex = dog.new fido.become_special fido.do_special_thing # okay! rex.do_special_thing # nomethoderror

ruby object type-conversion

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -