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

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." 

Leave a Comment