1

I have a string within a variable that contains a placeholder. So quite literally I have this:

x = "something_\#{environment}"

I want to perform placeholder substitution of x at runtime with a value of environment that isn't available at the point x is defined. I ultimately want to end up with:

y = "something_test"

Is there any way to accomplish this in Ruby?

Edit 1: this isn't solved using eval which is dead. Hence the linked duplicate doesn't address my question.

et071385
  • 103
  • 9

1 Answers1

3

Use templates with %:

template = "something_%s"
#=> "something_%s"
x = template % ["test"]
#=> "something_test"
David Lilue
  • 597
  • 2
  • 14
  • 4
    `%` also supports named placeholders: `'something_%{environment}' % {environment: 'test'}` – Stefan Apr 12 '17 at 13:28
  • Named templates is exactly what I was looking for. Didn't know I could use names with %. Stefan if you put a new answer in I'll mark as accepted answer. – et071385 Apr 12 '17 at 17:37