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. =A0In other words:
>
>
> begClass =3D a.class
> a.changeToSomethingElse(42)
> endClass =3D a.class
>
> # Where begClass !=3D 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
> =A0def push(*els)
> =A0 =A0a =3D Array.new
> =A0 =A0a.push(*els)
> =A0 =A0#self =3D a =A0 =A0 =A0 =A0 =A0 =A0 # Nope!
> =A0 =A0#self.class =3D Array =A0 # Nope!
> =A0end
> end
>
> This would allow:
> =A0a =3D nil
> =A0a.push(1,2,3)
> =A0puts "#{a.class}"
>
> I know we have things like to_a, but that requires an assigment instead
> of just the method call. =A0Let'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 =3D nil
...
(a ||=3D[]).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? =A0I 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

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/