In Ruby you can reference variables inside strings and they are interpolated at runtime.
For example if you declare a variable foo
equals \"Ted\
Instead of interpolating, you could use erb. This blog gives simple example of ERB usage,
require 'erb'
name = "Rasmus"
template_string = "My name is <%= name %>"
template = ERB.new template_string
puts template.result # prints "My name is Rasmus"
Kernel#eval could be used, too. But most of the time you want to use a simple template system like erb
.
Might as well throw my own solution into the mix.
irb(main):001:0> str = '#{13*3} Music'
=> "\#{13*3} Music"
irb(main):002:0> str.gsub(/\#\{(.*?)\}/) { |match| eval($1) }
=> "39 Music"
The weakness is that the expression you want to evaluate may have further { } in it, so the regex should probably be improved.
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."
You can read the file into a string using IO.read(filename), and then use the result as a format string (http://www.ruby-doc.org/core-2.0/String.html#method-i-25):
myfile.txt:
My name is %{firstname} %{lastname} and I am here to talk about %{subject} today.
fill_in_name.rb:
sentence = IO.read('myfile.txt') % {
:firstname => 'Joe',
:lastname => 'Schmoe',
:subject => 'file interpolation'
}
puts sentence
result of running "ruby fill_in_name.rb" at the terminal:
My name is Joe Schmoe and I am here to talk about file interpolation today.
Ruby Facets provides a String#interpolate method:
Interpolate. Provides a means of extenally using Ruby string interpolation mechinism.
try = "hello"
str = "\#{try}!!!"
String.interpolate{ str } #=> "hello!!!"
NOTE: The block neccessary in order to get then binding of the caller.
The 2 most obvious answers have already been given, but if they don't to it for some reason, there's the format operator:
>> x = 1
=> 1
>> File.read('temp') % ["#{x}", 'saddle']
=> "The number of horses is 1, where each horse has a saddle\n"
where instead of the #{} magic you have the older (but time-tested) %s magic ...