What is Ruby equivalent of Python's `s= "hello, %s. Where is %s?" % ("John","Mary")`

PythonRubyString Formatting

Python Problem Overview


In Python, this idiom for string formatting is quite common

s = "hello, %s. Where is %s?" % ("John","Mary")

What is the equivalent in Ruby?

Python Solutions


Solution 1 - Python

The easiest way is string interpolation. You can inject little pieces of Ruby code directly into your strings.

name1 = "John"
name2 = "Mary"
"hello, #{name1}.  Where is #{name2}?"

You can also do format strings in Ruby.

"hello, %s.  Where is %s?" % ["John", "Mary"]

Remember to use square brackets there. Ruby doesn't have tuples, just arrays, and those use square brackets.

Solution 2 - Python

In Ruby > 1.9 you can do this:

s =  'hello, %{name1}. Where is %{name2}?' % { name1: 'John', name2: 'Mary' }

See the docs

Solution 3 - Python

Almost the same way:

"hello, %s. Where is %s?" % ["John","Mary"]
# => "hello, John. Where is Mary?"

Solution 4 - Python

Actually almost the same

s = "hello, %s. Where is %s?" % ["John","Mary"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - PythonAboutRubyView Answer on Stackoverflow
Solution 2 - PythontoongView Answer on Stackoverflow
Solution 3 - PythonManoj GovindanView Answer on Stackoverflow
Solution 4 - PythonphadejView Answer on Stackoverflow