在Python中,这个成语的字符串格式化是相当普遍的什么是Ruby的等效Python的`s =“hello,%s。%s是哪里?” %( “约翰福音”, “玛丽”)`
s = "hello, %s. Where is %s?" % ("John","Mary")
什么是Ruby中相同呢?
在Python中,这个成语的字符串格式化是相当普遍的什么是Ruby的等效Python的`s =“hello,%s。%s是哪里?” %( “约翰福音”, “玛丽”)`
s = "hello, %s. Where is %s?" % ("John","Mary")
什么是Ruby中相同呢?
最简单的方法是string interpolation。你可以直接在你的字符串中注入一小段Ruby代码。
name1 = "John"
name2 = "Mary"
"hello, #{name1}. Where is #{name2}?"
你也可以在Ruby中做格式化字符串。
"hello, %s. Where is %s?" % ["John", "Mary"]
记得在那里使用方括号。 Ruby没有元组,只有数组,而那些使用方括号。
几乎相同的方式:
irb(main):003:0> "hello, %s. Where is %s?" % ["John","Mary"]
=> "hello, John. Where is Mary?"
其实相差无几
s = "hello, %s. Where is %s?" % ["John","Mary"]
在Ruby 1.9,你可以这样做:
s = "hello, %{name1}. Where is %{name2} ?" % { :name1 => 'John', :name2 => 'Mary' }
编辑:添加缺少“:的
:name1 :name2 不是? – masnun 2012-08-04 07:46:59
我在* Idomatic Ruby *中编辑了相同的内容 - 但现在我注意到接受的答案已经做到了 - 再次删除了'编辑': -/ – toong 2014-08-07 11:16:20
当使用带有字符串%运算符的散列时,格式字符串不存在,你会得到一个KeyError。 – user1164178 2015-02-11 00:52:44
有没有字符串连接,只有字符串格式化。谷歌会回答这个问题,甚至比以往任何时候都更快......我花了大约20秒钟才发现,你可以在Ruby中完全相同。 – delnan 2010-08-24 07:39:10
你不是要求连接,而是要求格式化/替换。你应该改变你的问题。顺便说一下,在ruby中,使用+或<<运算符来执行连接。 – David 2010-08-24 07:49:00