The class-oriented idiom is very strict. I.e An object is an instance of a class. However, leaving classes behind, objects are nothing but state and behavior.In ruby and other purely object oriented languages, an object isn't judged on it's class but on it's behavior (ducktyping). Thus you don't need to change the class of an object ---which isn't much more than a factory to create object --- to achieve what you want. - Mixins allows you to inject behavior to objects at runtime. - It's possible to alter (undef) methods - You might want to github search for Mixology - Read about Role modeling (maybe DCI) and traits. On May 22, 2012, at 9:03 AM, Robert Klemme <shortcutter / googlemail.com> wrote: > On Tue, May 22, 2012 at 6:43 AM, David Madison <lists / ruby-forum.com> wrote: >> Let's start off with the assumption I want a method that allows an >> object to transform itself into another object. In other words: >> >> >> begClass = a.class >> a.changeToSomethingElse(42) >> endClass = a.class >> >> # Where begClass != endClass > > You can't do this. > >> As a more specific example, consider some hopeful code for allowing >> auto-creation of arrays from nil, perl-ish style: > > If you miss Perl that much you are probably using the wrong language here. >> class Nil >> def push(*els) >> a = Array.new >> a.push(*els) >> #self = a # Nope! >> #self.class = Array # Nope! >> end >> end >> >> This would allow: >> a = nil >> a.push(1,2,3) >> puts "#{a.class}" >> >> I know we have things like to_a, but that requires an assigment instead >> of just the method call. Let's just assume we need a way to do it like >> this. > > I am not ready to assume "that we need a way to do it like this". The > Ruby idiom for this is > > a = nil > ... > (a ||=[]).push(1,2,3) > >> Is this just considered impossible, or is there a way to change/convert >> the class of self from inside a method? I can imagine it would cause >> complications the moment the class changes, since we'd suddenly be in >> the method of the wrong class, but if any language had a way to do it, I >> figure it'd be ruby. > > There might be a way in a C extension but actually I consider it a bad > idea because it violates one of the basic assumptions of the language > (i.e. that the class of an instance does not change) - and it's > unnecessary (see above). > > What you can do is to use a proxy object like SimpleDelegator and > change the instance it points to later. But then you need to > initialize the variable and if you know it's going to be an Array you > can just as well initialize with an empty Array instance. > > Kind regards > > robert > > -- > remember.guy do |as, often| as.you_can - without end > http://blog.rubybestpractices.com/ >