Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation with actual % in string

Tags:

What's the right way to deal with this?

"Hi %s, today is %s so you get 10% OFF!" % ['Joe', 'Monday']
# => ArgumentError: malformed format string - %O

I can't use normal %{keyname} or #{code} because I'm parsing strings for urls and stripping them out so I can stick them back in different formats (with/without protocol, shortened, full length, etc). So the number of replacements is unknown and they don't have names. They are just an array of urls.

I also tried escaping the %:

"Hi %s, today is %s so you get 10\% OFF!" % ['Joe', 'Monday']
# => ArgumentError: malformed format string - %O

but get the exact same result.

like image 224
eagspoo Avatar asked Nov 17 '12 15:11

eagspoo


People also ask

How is string interpolation performed?

String interpolation is a process substituting values of variables into placeholders in a string. For instance, if you have a template for saying hello to a person like "Hello {Name of person}, nice to meet you!", you would like to replace the placeholder for name of person with an actual name.

Can we use expressions Inside string interpolation?

The string interpolation result is 'Hello, World!' . You can put any expression inside the placeholder: either an operator, a function call, or even more complex expressions. ${n1 + n2} is a placeholder consisting of the addition operator and 2 operands.

What is string interpolation and explain with example?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

What happens if you use NULL value in string interpolation?

If the interpolation expression evaluates to null , an empty string ("", or String.


2 Answers

Two %'s

>> "Hi %s, today is %s so you get 10%% OFF!" % ['Joe', 'Monday']
=> "Hi Joe, today is Monday so you get 10% OFF!"
like image 199
Sean Redmond Avatar answered Sep 20 '22 03:09

Sean Redmond


 "Hi %s, today is %s so you get 10%% OFF!" % ['Joe', 'Monday']
like image 24
MarkW Avatar answered Sep 22 '22 03:09

MarkW