On Sun, Aug 5, 2012 at 7:19 PM, Andrea Dallera <[email protected]> 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 > <redefine ClassA to ClassB in some way, for ev only> > 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
That can lead to confusion with regard to the class names. > Ideas? Well, the simplest is to just store it in a member. irb(main):001:0> Evaluator = Struct.new :other_class do irb(main):002:1* def evaluate; other_class; end irb(main):003:1> end => Evaluator irb(main):004:0> class A;end => nil irb(main):005:0> class B;end => nil irb(main):006:0> e1 = Evaluator.new A => #<struct Evaluator other_class=A> irb(main):007:0> e1.evaluate => A irb(main):008:0> e2 = Evaluator.new B => #<struct Evaluator other_class=B> irb(main):009:0> e2.evaluate => B Note: you do not necessarily need the Struct, I just picked it because that saved me a bit of typing. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ -- You received this message because you are subscribed to the Google Groups ruby-talk-google group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at https://groups.google.com/d/forum/ruby-talk-google?hl=en
