在编写 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
或者,可选地,用 gsub 来修复缩进 https://stackoverflow.com/questions/3772864/how-do-i-remove-leading-whitespace-chars-from-ruby-heredoc-问题(哎哟!?)。
连接。
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
(引用自塞缪尔·L·伊普苏姆 http://slipsum.com/ )
我知道在我的脚本中使用这样的字符串(即视图逻辑)本身就是一种味道,但不知道有什么模式(除了 po 文件等)可以清理它。