在Python中,这种字符串格式化的习惯用法非常普遍
s = "hello, %s. Where is %s?" % ("John","Mary")
在 Ruby 中等价的是什么?
在Python中,这种字符串格式化的习惯用法非常普遍
s = "hello, %s. Where is %s?" % ("John","Mary")
在 Ruby 中等价的是什么?
最简单的方法是使用字符串插值。你可以直接将小片段的 Ruby 代码注入到你的字符串中。
name1 = "John"
name2 = "Mary"
"hello, #{name1}. Where is #{name2}?"
在Ruby中,您也可以使用格式化字符串。
"hello, %s. Where is %s?" % ["John", "Mary"]
记得使用方括号。Ruby 没有元组,只有数组,而数组使用方括号。
'#{name1}'
与"#{name1}"
不同。 - yurisich'#{"abc"}' # => "\#{\"abc\"}"
,但你想要的是 "#{"abc"}" # => "abc"
。 - bschlueter在 Ruby > 1.9 版本中,你可以这样做:
s = 'hello, %{name1}. Where is %{name2}?' % { name1: 'John', name2: 'Mary' }
几乎一样的方式:
"hello, %s. Where is %s?" % ["John","Mary"]
# => "hello, John. Where is Mary?"
s = "hello, %s. Where is %s?" % ["John","Mary"]