Created
November 15, 2024 17:58
-
-
Save gecugamo/aa0a3101e742b5d02f8fafd3fa78191a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def transform_templated_string(template, replacements) | |
# Ensure replacements keys are valid | |
replacements.each_key do |key| | |
unless /^[a-z_]+$/i.match?(key.to_s) | |
raise ArgumentError, 'keys may only consist of letters and underscores' | |
end | |
end | |
# Perform the replacements | |
replacements.reduce(template) do |transformed_string, (key, value)| | |
key_pattern = /%\{#{key}\}/ | |
transformed_string.gsub(key_pattern, value.to_s) | |
end | |
end | |
result = transform_templated_string( | |
'Cannot have insurance score less than %{minimum_insurance_score} and insurance lapse of %{minimum_days_for_lapse} or more days', | |
{minimum_insurance_score: '100', minimum_days_for_lapse: 5, foo: 'bar'} | |
) | |
puts result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment