Ruby 相当于 Python 的 `s="hello, %s.Where is %s?" %(“约翰”,“玛丽”)`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3554344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is Ruby equivalent of Python's `s= "hello, %s. Where is %s?" % ("John","Mary")`
提问by TIMEX
In Python, this idiom for string formatting is quite common
在 Python 中,这种字符串格式化的习惯用法很常见
s = "hello, %s. Where is %s?" % ("John","Mary")
What is the equivalent in Ruby?
Ruby 中的等价物是什么?
采纳答案by AboutRuby
The easiest way is string interpolation. You can inject little pieces of Ruby code directly into your strings.
最简单的方法是字符串插值。您可以将一小段 Ruby 代码直接注入到您的字符串中。
name1 = "John"
name2 = "Mary"
"hello, #{name1}. Where is #{name2}?"
You can also do format strings in Ruby.
您还可以在 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.
请记住在那里使用方括号。Ruby 没有元组,只有数组,而且那些使用方括号。
回答by Manoj Govindan
Almost the same way:
几乎相同的方式:
irb(main):003:0> "hello, %s. Where is %s?" % ["John","Mary"]
=> "hello, John. Where is Mary?"
回答by phadej
Actually almost the same
其实几乎一样
s = "hello, %s. Where is %s?" % ["John","Mary"]
回答by toong
In Ruby > 1.9 you can do this:
在 Ruby > 1.9 中,你可以这样做:
s = 'hello, %{name1}. Where is %{name2}?' % { name1: 'John', name2: 'Mary' }

