Constructing format string using variables
The string format works like this:
someString = "Example string %{key}"
result = someString % {key: newData}
I would like to get hash keys in a string without hardcoding them. Is there a way to do this?
Also is there a way to construct a format string using variables? I would like to do something like this:
variable = key
result = someString % {variable: newData}
+3
source to share
2 answers
One way to extract keys from format string:
"Example string %{key1} %{key2}".scan /(?<=%{)[^{}]+?(?=})/
# => ["key1", "key2"]
The regex (?<=%{)[^{}]+?(?=})
matches one or more characters (not greedy) if it is prefixed %{
and then }
.
To plot a format string, you can use string interpolation:
variable = 'key'
"Example string %{#{variable}}"
# => "Example string %{key}"
+2
source to share