Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do "late" string interpolation in Ruby

Tags:

ruby

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

like image 558
Paweł Gościcki Avatar asked Sep 12 '11 18:09

Paweł Gościcki


People also ask

What is string interpolation 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.

What's the difference between concatenation and interpolation Ruby?

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.

What is interpolated string in C#?

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.

What is swift interpolation?

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.


2 Answers

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!" 
like image 154
nathanvda Avatar answered Sep 30 '22 17:09

nathanvda


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.

like image 34
tadman Avatar answered Sep 30 '22 17:09

tadman