在Ruby中以编程方式构建多行字符串

在Ruby中以编程方式构建多行字符串,ruby,Ruby,以下是我在编程时经常做的事情: code = '' code << "next line of code #{something}" << "\n" code << "another line #{some_included_expression}" << "\n" 使用这将是一种方法: code = [] code << "next line of code #{something}" code << "another

以下是我在编程时经常做的事情:

code = ''
code << "next line of code #{something}" << "\n"
code << "another line #{some_included_expression}" << "\n"
使用这将是一种方法:

code = []
code << "next line of code #{something}"
code << "another line #{some_included_expression}"
code.join("\n")
code=[]
代码这里介绍了一种方法:


我想问题是:monkey patching缺乏可移植性/存在性是否会使此解决方案变得糟糕。

我想,您只需在字符串中嵌入…\n“就行了。下面是一个有趣的方法:

class String
  def / s
    self << s << "\n"
  end
end
这将启用以下功能:

"" / "line 1" / "line 2" / "line 3" # => "line 1\nline 2\nline 3\n"
甚至:

f/
"line one"/
"line two"/
"line three"     # => "line one\nline two\nline three\n"

如果要生成文本块,最简单的方法是使用%运算符。例如:

code = %{First line
second line
Third line #{2 + 2}}
“代码”将被删除

"First line\n second line\n Third line 4"

您可以将多行文本放在一个文件中,并使用ERB对其进行解析(注意,ERB包含在Ruby中)

(ERB可以从绑定访问变量,该绑定是一个对象,提供对另一个对象拥有的实例方法和变量的访问。通过将其设置为“绑定”,它指向自身)

文档。

有什么问题:

code = "next line of code #{something}\n"+
       "another line #{some_included_expression}"

这看起来很不错(我想这是一个HERE文档),但它会在行的开头保留空格。有没有办法消除这种情况?
code=close,但我也希望它保留缩进…应该去掉的只是多余的空格。是的,我知道一种解决方法,但它很难看。你为什么要在herdoc?o0中保留缩进,而不必在|“为每一行添加前缀并更改字符串类,为什么不直接使用“code您可能会丢失变量:
[“first line”,“second line”]”。join(“\n”)
+1。同样,对于阅读此内容的人,您不需要使用%{String}…任何字符都可以。例如%-String-或%%String。”~
"" / "line 1" / "line 2" / "line 3" # => "line 1\nline 2\nline 3\n"
f/
"line one"/
"line two"/
"line three"     # => "line one\nline two\nline three\n"
code = %{First line
second line
Third line #{2 + 2}}
"First line\n second line\n Third line 4"
require 'erb'

multi_line_string = File.open("multi_line_string.erb", 'r').read
template = ERB.new(multi_line_string)
template.result(binding)
code = "next line of code #{something}\n"+
       "another line #{some_included_expression}"