问题: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"]

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。