在编写 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 来修复标识问题(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 左右)来清理它。