In Ruby, can you perform string interpolation on data read from a file?

Teflon Ted picture Teflon Ted · Dec 6, 2008 · Viewed 15.8k times · Source

In Ruby you can reference variables inside strings and they are interpolated at runtime.

For example if you declare a variable foo equals "Ted" and you declare a string "Hello, #{foo}" it interpolates to "Hello, Ted".

I've not been able to figure out how to perform the magic "#{}" interpolation on data read from a file.

In pseudo code it might look something like this:

interpolated_string = File.new('myfile.txt').read.interpolate

But that last interpolate method doesn't exist.

Answer

DavidG picture DavidG · Jun 29, 2011

I think this might be the easiest and safest way to do what you want in Ruby 1.9.x (sprintf doesn't support reference by name in 1.8.x): use Kernel.sprintf feature of "reference by name". Example:

>> mystring = "There are %{thing1}s and %{thing2}s here."
 => "There are %{thing1}s and %{thing2}s here."

>> vars = {:thing1 => "trees", :thing2 => "houses"}
 => {:thing1=>"trees", :thing2=>"houses"}

>> mystring % vars
 => "There are trees and houses here."