From: Stefano Crocco Date: 2007-05-21T21:02:59+09:00 Subject: Re: Simple Q: object creation to be determined by incoming data Alle luned� 21 maggio 2007, Todd Benson ha scritto: > I'm almost embarrassed to ask this, because I'm bound to be pointed to some > code that I've almost certainly read already, but here goes my ruby newbie > question: > > I have an incoming stream of data in separated chunks, each having a > beginning word that defines that chunk's place in the world (how it will > respond to #to_s, etc). Currently, I model each chunk as an object; each > has its own class. Basically, I'm unserializing object data, but I provide > the object functionality. I want to do off-the-stream object creation, and > so I've went and done something like: > > instance_eval( "#{class_name_from_stream_chunk}.new( data_from_stream_chunk > )" ) > > Is this the only way to do this (by "way", I mean the code and also the > manner), and if not, the best way? I'm not sure I understand correctly your question. I think you don't need to use instance eval. If class_name_from_stream_chunk is a string/symbol and the class is defined in the module M (if it is defined top level, substitute M with Kernel), you can do: M.const_get(class_name_from_stream_chunk).new(data_from_stream_chunk) You can also define a method which wraps this in a simpler interface: def M.new_from_chunk name, data const_get(name).new(data) end and use it this way: res = M.new(class_name_from_stream_chunk, data_from_stream_chunk) I hope this helps Stefano