Search code examples
rubystringinterpolation

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


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.


Solution

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