Ruby相当于Python的`s =“你好,%s。%s在哪里?” %(“ John”,“ Mary”)`

问题:Ruby相当于Python的`s =“你好,%s。%s在哪里?” %(“ John”,“ Mary”)`

在Python中,这种用于字符串格式化的习惯很普遍

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

Ruby中的等效功能是什么?

In Python, this idiom for string formatting is quite common

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

What is the equivalent in Ruby?


回答 0

最简单的方法是字符串插值。您可以将少量Ruby代码直接注入您的字符串中。

name1 = "John"
name2 = "Mary"
"hello, #{name1}.  Where is #{name2}?"

您也可以在Ruby中格式化字符串。

"hello, %s.  Where is %s?" % ["John", "Mary"]

请记住在此处使用方括号。Ruby没有元组,只有数组,并且使用方括号。

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.


回答 1

在Ruby> 1.9中,您可以执行以下操作:

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

查看文件

In Ruby > 1.9 you can do this:

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

See the docs


回答 2

几乎相同的方式:

irb(main):003:0> "hello, %s. Where is %s?" % ["John","Mary"]
=> "hello, John. Where is Mary?"

Almost the same way:

irb(main):003:0> "hello, %s. Where is %s?" % ["John","Mary"]
=> "hello, John. Where is Mary?"

回答 3

其实差不多

s = "hello, %s. Where is %s?" % ["John","Mary"]

Actually almost the same

s = "hello, %s. Where is %s?" % ["John","Mary"]