Ruby : multiple string substitution in string template

30 Jan 2013

Consider the below string template in which you need to replace the product and cost with values dynamically.
It may be apple and 70 or Orange and 40 etc.

When to use String interpolation 

We can use string interpolation if we are using this in only one place.

It won't work when we need the reuse the template by assigning into a variable. Duplicating the template everywhere is bad and lead to unmaintainable code.

Why its better to use "%" method?

The easiest way to substitute multiple strings into a string template is using "%" method of String class.
In order to reuse the template we can assign it to a variable and pass the substituents into "%" method as an array or Hash.

Using Array

If you are using array

  • You should specify the placements as %s, %f or %d.
  • The order of substitutions should be maintained
  • The change in data type may result in errors.
  • You may need to format the output refer sprintf

Using Hash

For me using the Hash is the most continent and simple way. I can used named placements never need to think of the list of issues above.

If you find my work useful, I appreciate donations via PayPal.
comments powered by Disqus