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

Question:

In Python, this idiom for string formatting is quite common

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

What is the equivalent in Ruby?

Asked By: TIMEX

||

Answers:

Almost the same way:

"hello, %s. Where is %s?" % ["John","Mary"]
# => "hello, John. Where is Mary?"
Answered By: Manoj Govindan

Actually almost the same

s = "hello, %s. Where is %s?" % ["John","Mary"]
Answered By: phadej

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.

Answered By: AboutRuby

In Ruby > 1.9 you can do this:

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

See the docs

Answered By: toong
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.