9

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?

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.