Ruby中如何实现Python的`s= "hello, %s. Where is %s?" % ("John","Mary")`?
在Python中,这种字符串格式化的写法非常常见。
s = "hello, %s. Where is %s?" % ("John","Mary")
那在Ruby中有什么类似的写法呢?
相关问题:
4 个回答
22
几乎是一样的方式:
"hello, %s. Where is %s?" % ["John","Mary"]
# => "hello, John. Where is Mary?"
55
在 Ruby 1.9 及以上版本,你可以这样做:
s = 'hello, %{name1}. Where is %{name2}?' % { name1: 'John', name2: 'Mary' }
271
最简单的方法就是字符串插值。你可以直接把小段Ruby代码放进你的字符串里。
name1 = "John"
name2 = "Mary"
"hello, #{name1}. Where is #{name2}?"
你也可以在Ruby中使用格式化字符串。
"hello, %s. Where is %s?" % ["John", "Mary"]
记得在这里使用方括号。Ruby没有元组,只有数组,而数组是用方括号来表示的。