Ruby中如何实现Python的`s= "hello, %s. Where is %s?" % ("John","Mary")`?

155 投票
4 回答
100577 浏览
提问于 2025-04-16 03:13

在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没有元组,只有数组,而数组是用方括号来表示的。

撰写回答