From: James Edward Gray II Date: 2005-04-07T00:48:17+09:00 Subject: Re: Interpolating a string loaded from a text file On Apr 6, 2005, at 10:34 AM, John Elrick wrote: > Hoping you guys can help out here. Is there any way to interpolate a > string that is loaded dynamically? > > I know that in Ruby I can do this: > > my_message = 'Hello World' > my_template = "The message is #my_message" > puts my_template <== The message is Hello World Only if you replace #my_message with #{my_message}. ;) > But what I want to do is > > my_message = 'Hello World' > my_template = > File.readlines('my_template_file.txt').HOW-CAN-I-FORCE-INTERPOLATION??? > puts my_template <== The message is Hello World > > > Anyone have any ideas? Or am I missing something blatantly obvious? Well, there's always search and replace: template.gsub(/#\{\s*(\w+)\s*\}/) { # do something with $1 here... } I think that works pretty well with a Hash, keyed by the $1 values to interpolate. Option two is to call eval(). This executes Ruby code and returns the results. This naturally has security concerns, if you aren't in control of the template. Finally, you can make use of Ruby's standard template library, ERb: http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html Hope that helps. James Edward Gray II