Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 1000
Teflon Ted Avatar asked Dec 06 '08 15:12

Teflon Ted


People also ask

How do you interpolate a string in Ruby?

String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals.

How does string interpolation perform?

String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.

Can I use string interpolation?

Beginning with C# 10, you can use string interpolation to initialize a constant string. All expressions used for placeholders must be constant strings. In other words, every interpolation expression must be a string, and it must be a compile time constant.


3 Answers

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." 
like image 62
DavidG Avatar answered Oct 19 '22 17:10

DavidG


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"
like image 26
Daniel Lucraft Avatar answered Oct 19 '22 18:10

Daniel Lucraft


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.

like image 19
stesch Avatar answered Oct 19 '22 18:10

stesch