如何在 Ruby 中条件格式化字符串?

发布于 2024-12-23 06:19:23 字数 412 浏览 2 评论 0原文

这是我一段时间以来一直试图弄清楚但无法完全弄清楚的事情。

假设我有这四个元素:

  • 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

热情消退 2024-12-30 06:19:23

只需逐步构建字符串并组合结果即可。如果您有权访问 .blank,您可以轻松清理以下内容吗? (我认为它是空白的?)

parts = []
parts << name if name && !name.empty?
parts << "was" if name && !name.empty? && location && !location.empty?
parts << %{at location "#{location}"} if location && !location.empty?
parts << "around #{time}"
parts << "and" if location && !location.empty? && text && !text.emtpy?
parts << "said #{text}" if text && !text.empty?
parts.join(" ")

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?)

parts = []
parts << name if name && !name.empty?
parts << "was" if name && !name.empty? && location && !location.empty?
parts << %{at location "#{location}"} if location && !location.empty?
parts << "around #{time}"
parts << "and" if location && !location.empty? && text && !text.emtpy?
parts << "said #{text}" if text && !text.empty?
parts.join(" ")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文