From: Xavier Noria Date: 2012-08-06T03:32:06+09:00 Subject: Re: Redefining constants for a given instance only --f46d042de42364319304c688fa10 Content-Type: text/plain; charset=UTF-8 On Sun, Aug 5, 2012 at 7:19 PM, Andrea Dallera wrote: Hello, > > let's say we have two empty classes: > > class ClassA > > end > > class ClassB > > end > > then we have a third one, which has a method that references the first > class: > > class Evaluator > > def evaluate > return ClassA > end > > end > > What I'd like to do is to be able to redefine what ClassA is for a given > instance of Evaluator, like so: > > ev = Evaluator.new > > ev.evaluate #ClassB > > I found out how to do this, but only class-wide: > > ev = Evaluator.new > ev.evaluate #ClassA > class Evaluator > ClassA = ClassB > end > ev.evaluate #ClassB > > Ideas? > > Andrea > Constants are only storage, that method is returning a class object. The normal implementation would be def evaluate if some condition ClassA else ClassB end end because the caller gets a class object, the constant (or variable, or method call, or whatever) #evaluate happened to take the class object from is irrelevant to the caller. Now, I guess from your question that approach is not good for your problem, but in that case I'd like to understand why to suggest another one. --f46d042de42364319304c688fa10 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable On Sun, Aug 5, 2012 at 7:19 PM, Andrea Dallera <andrea@andreadaller= a.com> wrote:

Hello,<= /div>

=C2=A0 =C2=A0 let's say we have two empty clas= ses:

class ClassA

end

class ClassB

end

then we have a third one, which has a method that references the fir= st class:

class Evaluator
=C2=A0 =C2=A0<= /div>
=C2=A0 =C2=A0def evaluate
=C2=A0 =C2=A0 =C2=A0 =C2=A0return Class= A
=C2=A0 =C2=A0end

end

What I'd like to do is to be able to redefine what ClassA is fo= r a given instance of Evaluator, like so:

ev =3D Evaluator.new
<redefine ClassA to C= lassB in some way, for ev only>
ev.evaluate #ClassB
=
I found out how to do this, but only class-wide:

ev =3D Evaluator.new
ev.evaluate #ClassA
class Evaluator
=C2=A0 ClassA =3D ClassB
end
ev.evaluate #ClassB

Ideas?

Andrea

Constants are only storage, th= at method is returning a class object. The normal implementation would be

=C2=A0 =C2=A0 def evaluate
=C2=A0 =C2=A0 = =C2=A0 if some condition
=C2=A0 =C2=A0 =C2=A0 =C2=A0 ClassA
=C2=A0 =C2=A0 =C2=A0 else=
=C2=A0 =C2=A0 =C2=A0 =C2=A0 ClassB
=C2=A0 =C2=A0 =C2= =A0 end
=C2=A0 =C2=A0 end

because the ca= ller gets a class object, the constant (or variable, or method call, or wha= tever) #evaluate happened to take the class object from is irrelevant to th= e caller.

Now, I guess from your question that approach is not go= od for your problem, but in that case I'd like to understand why to sug= gest another one.

--f46d042de42364319304c688fa10--