Fix Python – What is Ruby equivalent of Python’s `s= “hello, %s. Where is %s?” % (“John”,”Mary”)`

Question

Asked By – TIMEX

In Python, this idiom for string formatting is quite common

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

What is the equivalent in Ruby?

Now we will see solution for issue: What is Ruby equivalent of Python’s `s= “hello, %s. Where is %s?” % (“John”,”Mary”)`


Answer

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.

This question is answered By – AboutRuby

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0