From: Brian Candler Date: 2012-08-06T16:53:36+09:00 Subject: Re: Redefining constants for a given instance only module Ctx1 class A def foo; 1; end end class B def bar; 2; end end end module Ctx2 class A def foo; 4; end end class B def bar; 5; end end end class Evaluator def run(a) a ? Ctx1 : Ctx2 end end code = "A.new.foo + B.new.bar" puts Evaluator.new.run(true).module_eval code # 3 puts Evaluator.new.run(false).module_eval code # 9 Here, Evaluator#run returns a module, and that sets the namespace for the constant resolution in the eval of code. However, as Robert points out, classes are just regular objects in Ruby, and so can be passed around and used as such. It's perfectly normal and reasonable to return classes in variables, so you don't have to mess around with eval (which is often a security risk anyway) class Evaluator def run(a) a ? [Ctx1::A,Ctx1::B] : [Ctx2::A,Ctx2::B] end end a, b = Evaluator.new.run(true) puts a.new.foo + b.new.bar a, b = Evaluator.new.run(false) puts a.new.foo + b.new.bar That is, the variables a and b contain classes, and you use them directly, independent of the fact that they happen to be bound to constants like Ctx1::A. In fact, you can also have completely anonymous classes (using Class.new) -- Posted via http://www.ruby-forum.com/.