【发布时间】:2023-03-21 21:17:01
【问题描述】:
在编写 Ruby(客户端脚本)时,我看到了三种构建更长字符串的方法,包括行尾,所有这些对我来说都“闻起来”有点难看。
有没有更干净更好的方法?
变量递增。
if render_quote?
quote = "Now that there is the Tec-9, a crappy spray gun from South Miami."
quote += "This gun is advertised as the most popular gun in American crime. Do you believe that shit?"
quote += "It actually says that in the little book that comes with it: the most popular gun in American crime."
quote += "Like they're actually proud of that shit."
puts quote
end
Heredocs(和未闭合的引号)。
if render_quote?
quote =<<EOS
Now that there is the Tec-9, a crappy spray gun from South Miami.
This gun is advertised as the most popular gun in American crime. Do you believe that shit?
It actually says that in the little book that comes with it: the most popular gun in American crime.
Like they're actually proud of that shit.
EOS
puts quote
end
或者,不添加结束标签:
if render_quote?
quote = "Now that there is the Tec-9, a crappy spray gun from South Miami.
This gun is advertised as the most popular gun in American crime. Do you believe that shit?
It actually says that in the little book that comes with it: the most popular gun in American crime.
Like they're actually proud of that shit."
puts quote
end
或者,可选地,with a gsub to fix the identation-issues (yuk!?)。
连接。
if render_quote?
quote = "Now that there is the Tec-9, a crappy spray gun from South Miami."
quote += "This gun is advertised as the most popular gun in American crime. Do you believe that shit?"
quote += "It actually says that in the little book that comes with it: the most popular gun in American crime."
quote += "Like they're actually proud of that shit."
puts quote
end
(引用自Samuel L. Ipsum)
我知道在我的脚本中包含这样的字符串(即视图逻辑)本身就是一种气味,但不知道有什么模式(除了 po-files 左右)来清理它。
【问题讨论】:
-
您的连接与变量递增有何不同?您是否两次列出相同的内容?
-
@SergioTulentsev 这是我编造的名字:)。因为 foo++ 和 foo+= 是“增量”更新 var。你在这里也做同样的事情。
标签: ruby string messages heredoc