From: David Alan Black Date: 2001-01-29T04:30:17+09:00 Subject: [ruby-talk:10028] dynamic class creation question Hello -- I'm trying to hone my skills at manipulating classes and methods. The following example/question is taken in isolation from a current project. The idea is to pass a string to FirstStage#new, and get back a Class object. Instances of that second class then do things (#showstuff) which have knowledge of the words in that original string. The way I'm doing it right now feels a bit awkward. I'm wondering if there's a nicer way to get a dynamically-created class to be able to see and use variables from the instance that's creating it (as opposed to using class variables in a quasi-global-variable way, which is what I'm currently doing). Here's the little example: ---------------------------------------------------- class FirstStage attr_accessor :words def initialize(s) @@w = s.split def FirstStage.words # Is this the only way to @@w # make the thing visible end # in another class's context? end def second_class c = Class.new c.class_eval <<-EOE attr_accessor :stuff def initialize self.stuff = FirstStage.words # Namely, right here. end def showstuff self.stuff.each do |t| puts t.upcase end end EOE return c end end # Test run f = FirstStage.new("These are some words") s = f.second_class p = s.new p.showstuff # THESE\nARE\nSOME\nWORDS\n ----------------------------------------------------------- Thanks for any pointers -- David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav