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

Pet*_*ter 17 ruby

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

code = ''
code << "next line of code #{something}" << "\n"
code << "another line #{some_included_expression}" << "\n"
Run Code Online (Sandbox Code Playgroud)

有没有比拥有<< "\n"+ "\n"在每条线上更好的方法?这似乎效率很低.

我特别感兴趣的是Ruby解决方案.我在想类似的东西

code = string.multiline do
  "next line of code #{something}"
  "another line #{some_included_expression}"
end
Run Code Online (Sandbox Code Playgroud)

Har*_*tum 29

如果您正在构建一个文本块,那么简单的方法就是使用%运算符.例如:

code = %{First line
second line
Third line #{2 + 2}}
Run Code Online (Sandbox Code Playgroud)

那么'代码'将是

"First line\n second line\n Third line 4"
Run Code Online (Sandbox Code Playgroud)

  • +1.另外,对于那些阅读此内容的人,您不需要使用%{string} ...任何角色都可以.例如%-string-或%~string~ (2认同)

Jim*_*Jim 18

这将是一种方式:

code = []
code << "next line of code #{something}"
code << "another line #{some_included_expression}"
code.join("\n")
Run Code Online (Sandbox Code Playgroud)

  • 你可以丢失变量:`["第一行","第二行"] .join("\n")` (4认同)

Eim*_*tas 9

使用<< - 运算符:

code = <<-CODE
var1 = "foo"
var2 = "bar"
CODE
Run Code Online (Sandbox Code Playgroud)


Dig*_*oss 5

我想你可以在你的琴弦中嵌入...... \n".这是一种有趣的方法:

class String
  def / s
    self << s << "\n"
  end
end
Run Code Online (Sandbox Code Playgroud)

然后

f = ""           # => ""
f / 'line one'   # => "line one\n"
f / 'line two'   # => "line one\nline two\n"
f / 'line three' # => "line one\nline two\nline three\n"
Run Code Online (Sandbox Code Playgroud)

这将使以下内容成为:

"" / "line 1" / "line 2" / "line 3" # => "line 1\nline 2\nline 3\n"
Run Code Online (Sandbox Code Playgroud)

甚至:

f/
"line one"/
"line two"/
"line three"     # => "line one\nline two\nline three\n"
Run Code Online (Sandbox Code Playgroud)