What is Ruby equivalent of Python's `s= “hello, %s. Where is %s?” % (“John”,“Mary”)`

扶醉桌前 提交于 2019-11-28 14:31:58

问题


In Python, this idiom for string formatting is quite common

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

What is the equivalent in Ruby?


回答1:


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.




回答2:


In Ruby > 1.9 you can do this:

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

See the docs




回答3:


Almost the same way:

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



回答4:


Actually almost the same

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


来源:https://stackoverflow.com/questions/3554344/what-is-ruby-equivalent-of-pythons-s-hello-s-where-is-s-john-mar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!