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


You almost got it. Just a little syntax



variable = :key # get this one from whereever
someString = "Example string %{key}"
someString % { variable => 'foo' } # => "Example string foo"

      

+2


source


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







All Articles