Search code examples
rubystringstring-interpolationlanguage-comparisons

Ruby string interpolation equivalent to python's .format()


In python I can do

_str = "My name is {}"
...
_str = _str.format("Name")

In ruby when I try

_str = "My name is #{name}"

The interpreter complains that the variable name is undefined, so it's expecting

_str = "My name is #{name}" => {name =: "Name"}

How can I have a string placeholder in ruby for later use?


Solution

  • You can use Delayed Interpolation.

    str = "My name is %{name}"
    # => "My name is %{name}"
    
    puts str % {name: "Sam"}
    # => "My name is Sam"
    

    The %{} and % operators in Ruby allows delaying the string interpolation until later. The %{} defines named placeholders in the string and % binds a given input into the placeholders.