Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
Sam Hammamy Avatar asked Dec 05 '22 22:12

Sam Hammamy


1 Answers

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.

like image 121
rastasheep Avatar answered Dec 30 '22 11:12

rastasheep