views:

1606

answers:

3

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.

+4  A: 

Instead of interpolating, you could use erb.

Kernel#eval could be used, too. But most of the time you want to use a simple template system like erb.

stesch
Or perhaps using something like liquid would be safer. It's the same concept as erb without the ability for malicious users to damage your application.
Vertis
+4  A: 

Well, I second stesch's answer of using erb in this situation. But you can use eval like this. If data.txt has contents:

he #{foo} he

Then you can load and interpolate like this:

str = File.read("data.txt")
foo = 3
result = eval("\"" + str + "\"")

And result will be:

"he 3 he"
Daniel Lucraft
and as always, be careful with your eval's
rampion
rampion is right. And this is important with every language that has such a feature.
stesch
A: 

The 2 most obvious answers have already been give, 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 ...

Purfideas