如何在 Ruby 中条件格式化字符串?
这是我一段时间以来一直试图弄清楚但无法完全弄清楚的事情。
假设我有这四个元素:
name = "Mark"
location = ""
time = Time.now
text - "foo "
如果我使用 str#%
进行格式化,如下所示: "%s 位于 %s 周围的位置 \"%s\" 并表示 %s" % [名称,位置,时间,文本]
,我该如何避免空格和孤立词的问题? (例如,“Mark 在 2011-12-28T020500Z-0400 左右位于“位置”并说“foo”)
我还可以使用其他技术吗?
This is something that I have been trying to figure out for a while but cannot quite figure it out.
Let's say I have these four elements:
name = "Mark"
location = ""
time = Time.now
text - "foo"
And if I used str#%
for formatting, like so: "%s was at the location \"%s\" around %s and said %s" % [name,location,time.to_s,text]
, how would I avoid the problem of blank spaces and orphaned words? (For example, "Mark was at the location "" around 2011-12-28T020500Z-0400 and said foo")
Are there any other techniques that I could use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需逐步构建字符串并组合结果即可。如果您有权访问 .blank,您可以轻松清理以下内容吗? (我认为它是空白的?)
Just build the string piecemeal and assemble the results. You could easily cleanup the following if you had access to .blank? (I think it's blank?)