From: "David A. Black" Date: 2005-07-21T01:33:14+09:00 Subject: Re: Variable class (newb question) Hi -- On Wed, 20 Jul 2005, Shaun Fanning wrote: > I'm trying to figure out how to use Ruby to implement a strategy type > pattern that I used in PHP. Basically I took a set of class names passed in > as variables and instantiated the right class depending on the value of the > variable. It was roughly something like: > > Class SurveyQuestion > drawQuestion > storeResponse > reportResponse > ... > > Class SurveyQuestionMultiChoice extends SurveyQuestion > Class SurveyQuestionCheckBox extends SurveyQuestion > ...etc. > > //build a list of question types based on what the user just submitted > $these_survey_questions = array('MultiChoice', 'MultiChoice', 'CheckBox') > > For each $these_survey_questions as $index=$question_type > $class_name = "SurveyQuestion".$question_type > $q = new $class_name() > $q.storeResponse($response_from_this_user) > > > So I'm struggling to figure out how this type of thing would typically be > done using Ruby. Or maybe it's a bad approach to this type of situation to > begin with so feel free to offer an alternative. Thanks. This might be a good case for a class method approach: class Survey class Question def self.store_response(kind, body) case kind when "multichoice" # ... when "checkbox" # ... # etc. end end end end and then if you can get your kinds and your responses into, say, an array of little arrays: questions.each {|q| Survey::Question.store_response(*q) } where q, each time, would be something like: ["checkbox","D"]. Another possibility (but I'd have to see more of how your data is being passed around to know) might be some kind of serialization that ended up with an array of objects that knew their own class, and knew how to store themselves -- resulting in something like: questions = questions.each {|q| q.store_response } which is, as they say, "more OO". David -- David A. Black dblack@wobblini.net