什么是Ruby相当于Python的`s ="你好,%s.%s在哪里?" %("约翰","玛丽")`

TIM*_*MEX 140 ruby python string-formatting

在Python中,这种用于字符串格式化的习惯用法很常见

s = "hello, %s. Where is %s?" % ("John","Mary")
Run Code Online (Sandbox Code Playgroud)

Ruby中的等价物是什么?

Abo*_*uby 242

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

name1 = "John"
name2 = "Mary"
"hello, #{name1}.  Where is #{name2}?"
Run Code Online (Sandbox Code Playgroud)

您还可以在Ruby中格式化字符串.

"hello, %s.  Where is %s?" % ["John", "Mary"]
Run Code Online (Sandbox Code Playgroud)

记得在那里使用方括号.Ruby没有元组,只有数组,而那些使用方括号.

  • 你也应该小心**总是使用双引号**因为`'#{name1}'`与`"#{name1}"`不一样. (11认同)
  • 字符串插值在单引号中不起作用,必须使用双引号.例如:`'#{"abc"}'#=>"\#{\"abc \"}"`,但你想要的是`"#{"abc"}"#=>"abc"` (3认同)
  • 第一种方法不是等效的-模板不能作为值传递。 (2认同)

too*_*ong 51

在Ruby> 1.9中你可以这样做:

s =  'hello, %{name1}. Where is %{name2}?' % { name1: 'John', name2: 'Mary' }
Run Code Online (Sandbox Code Playgroud)

查看文档


Man*_*dan 19

几乎相同的方式:

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

  • Ruby没有元组(至少没有伪造成语言).是的,它是一个数组(Python中的"列表"应该真的称为数组......). (3认同)

pha*_*dej 9

其实几乎一样

s = "hello, %s. Where is %s?" % ["John","Mary"]
Run Code Online (Sandbox Code Playgroud)