tuulik
tuulik

Reputation: 75

Constructing a format string using variables

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

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

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

Yu Hao
Yu Hao

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

Related Questions