views:

117

answers:

3

From Python...

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

How do you do that in Ruby?

+3  A: 

Almost the same way:

irb(main):003:0> "hello, %s. Where is %s?" % ["John","Mary"]
=> "hello, John. Where is Mary?"
Manoj Govindan
In Ruby, do the square brackets mean a tuple? I thought square brackets are lists...
TIMEX
@TIMEX: This question will help: http://stackoverflow.com/questions/525957/tuples-in-ruby
Manoj Govindan
Ruby doesn't have tuples (at least not forged into the language). Yeah, it's an array ("list" in Python should really be called arrays...).
delnan
+1  A: 

Actually almost the same

s = "hello, %s. Where is %s?" % ["John","Mary"]
phadej
+8  A: 

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.

AboutRuby
I would definitively use the first one, it looks more readable to me
David
The first one won't work, the #{} looks for a variable, so in this case it'd be printing the John variable, not the string "John".The second one looks correct.
Jason Noble
Good point Jason, I'll edit it to make it more clear.
AboutRuby