8

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Sam Hammamy
  • 10,819
  • 10
  • 56
  • 94

3 Answers3

19

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.

rastasheep
  • 10,416
  • 3
  • 27
  • 37
0

The interpreter is not expecting a hash, it's expecting a variable named name.

name = "Sam"
p str = "My name is #{name}" # => "My name is Sam"

The % method can be used as @rastasheep demonstrates. It can be used in a simpler way:

str = "My name is %s"
p str % "Name" # => "My name is Name"
steenslag
  • 79,051
  • 16
  • 138
  • 171
0

Based on the previous answers, you can use %s in place of {} for simplicity and flexibility. Use array instead of string if you have multiple unnamed place holders.

_str = "%s is a %s %s"
...
_str % %w(That nice movie)  # => "That is a nice movie"
John Doe
  • 1,364
  • 1
  • 12
  • 19