It looks like you want to create the basis for a template system that Ruby makes easy if you use String gsub or sub methods.
replacements = { '%greeting%' => 'Hello', '%name%' => 'Jim' } pattern = Regexp.union(replacements.keys) '%greeting% %name%!'.gsub(pattern, replacements) => "Hello Jim!"
You can also easily define a key as:
replacements = { '#{name}' => 'Jim' }
and use standard Ruby string interpolation #{...} , but I would recommend not using it again. Use something unique instead.
The advantage of this is that the target => replacement map can easily be placed in a YAML file or in a database table, and then you can replace them with other languages ββor different user data. The sky is the limit.
Evaluation is also not in favor of this, it is only a replacement string. With a little creative use, you can implement macros:
macros = { '%salutation%' => '%greeting% %name%' } replacements = { '%greeting%' => 'Hello', '%name%' => 'Jim' } macro_pattern, replacement_pattern = [macros, replacements].map{ |h| Regexp.union(h.keys) } '%salutation%!'.gsub(macro_pattern, macros).gsub(replacement_pattern, replacements) => "Hello Jim!"
source share