Reputation: 75
String format works like this:
someString = "Example string %{key}"
result = someString % {key: newData}
I would like to retrieve the hash keys in the string without hardcoding them. Is there a method for doing this?
Also, is there any way to construct the format string using variables? I would like to do something like this:
variable = key
result = someString % {variable: newData}
Upvotes: 3
Views: 107
Reputation: 230531
You almost got it. Just a bit off with the syntax
variable = :key # get this one from whereever
someString = "Example string %{key}"
someString % { variable => 'foo' } # => "Example string foo"
Upvotes: 2
Reputation: 122493
One way to extract keys from the format string:
"Example string %{key1} %{key2}".scan /(?<=%{)[^{}]+?(?=})/
# => ["key1", "key2"]
The regex (?<=%{)[^{}]+?(?=})
matches one or more characters (non-greedy) if it's prefixed by %{
and followed by }
.
To construct the format string, you can use string interpolation:
variable = 'key'
"Example string %{#{variable}}"
# => "Example string %{key}"
Upvotes: 2