Ruby: Replace parts of a string

regex, replace, ruby, string

Solution

Instead doing search/replace, you can use `Kernel#sprintf` method, or its `%` shorthand. Combined with Hashes, it can come pretty handy:

'Hello, %{who}. You did %{what}' % {:who => 'Sal', :what => 'wrong'}
# => "Hello, Sal. You did wrong" 

The advantage of using Hash instead of Array is that you don't have to worry about the ordering, and you can have the same value inserted on multiple places in the string.

Problem

I have many strings following a certain pattern: ``` string = "Hello, @name. You did @thing." # example ``` Basically, my strings are a description where @word is dynamically. I need to replace each with a value at runtime. ``` string = "Hello, #{@name}. You did #{@thing}." # Is not an option! ``` The @word is basically a variable, but I just cannot use the method above. How should I do that?

Original source