>> string = '#{var}' => "\#{var}" >> proc = Proc.new { |var| string } => #<Proc:0xb717a8c4@(pry):6> >> proc.call(123) => "\#{var}"
Not really what I want. Double quotes around string
result in the obvious undefined local variable
.
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.
Concatenation allows you to combine to strings together and it only works on two strings. Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable.
An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6.
String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use string interpolation in both single-line and multiline string literals.
In my case I needed to have configuration stored inside a yml, with interpolation, but which is only interpolated when I need it. The accepted answer with the Proc
seemed overly complicated to me.
In ruby 1.8.7 you can use the %
syntax as follows:
"This is a %s verb, %s" % ["nice", "woaaaah"]
When using at least ruby 1.9.x (or ruby 1.8.7 with i18n) there is a cleaner alternative:
my_template = "This is a %{adjective} verb, %{super}!" my_template % { adjective: "nice", super: "woah" } => "This is a nice verb, woah!"
Although this is possible, it's not going to work how you intend here without having to use eval
, and generally that's a bad idea if there's an alternative. The good news is you have several options.
The most straightforward is to use sprintf
formatting which is made even easier with the String#%
method:
string = '%s' proc = Proc.new { |var| string % var } proc.call(123) # => "123"
This is a really reliable method as anything that supports the .to_s
method will work and won't cause the universe to implode if it contains executable code.
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