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.
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.
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.
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.
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."
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"
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With