Homepage
free software, web technologies and heavy metal coding (and ruby of course)

string variable interpolation from file in ruby

Sometimes you want to interpolate your variables from a dynamic string, e.g. some settings from a yaml file. The top three options are:

I’ll show the third option here as:

Ruby has string formatting support and a very handy % operator. This enables us to replace certain parts of our config at runtime with the actual value, like this:


"foo = %{foo}" % { :foo => 'bar' }

Metaflop serves once again as a sample application. The following shows the perl command to generate some parts of our fonts (simplified):
config.yml:


font_otf: perl mf2pt1.pl --family=%{fontface} --nofixedpitch --fullname="%{fontface} %{font_hash}" font.mf

Assuming we have a “config” variable that holds all the values defined in yaml we can do:


config.font_otf % {
  :fontface => 'Bespoke',
  :font_hash => '234sdof23nsf'}

# => perl mf2pt1.pl --family=Bespoke --nofixedpitch --fullname="Bespoke 234sdof23nsf" font.mf

The operator accepts literals and arrays as arguments as well, but I like the named parameters style best. This way, there is an obvious connection between the placeholder and its value.