这是我在编程时经常做的事情:
code = ''
code << "next line of code #{something}" << "\n"
code << "another line #{some_included_expression}" << "\n"
有没有比在每一行都有<< "\n"
或+ "\n"
更好的方式?这似乎效率很低。
我特别感兴趣的是Ruby解决方案。我在想像
code = string.multiline do
"next line of code #{something}"
"another line #{some_included_expression}"
end
答案 0 :(得分:28)
如果您正在构建一个文本块,那么简单的方法就是使用%运算符。例如:
code = %{First line
second line
Third line #{2 + 2}}
'code'将是
"First line\n second line\n Third line 4"
答案 1 :(得分:18)
这将是一种方式:
code = []
code << "next line of code #{something}"
code << "another line #{some_included_expression}"
code.join("\n")
答案 2 :(得分:9)
使用&lt;&lt; - operator:
code = <<-CODE
var1 = "foo"
var2 = "bar"
CODE
答案 3 :(得分:5)
我认为你可以在你的琴弦中嵌入...... \ n“。这是一种有趣的方式:
class String
def / s
self << s << "\n"
end
end
然后
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"
这样就可以实现:
"" / "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"
答案 4 :(得分:3)
以下是here提供的方法:
str = <<end.margin
|This here-document has a "left margin"
|at the vertical bar on each line.
|
| We can do inset quotations,
| hanging indentions, and so on.
end
这可以通过以下方式实现:
class String
def margin
arr = self.split("\n") # Split into lines
arr.map! {|x| x.sub!(/\s*\|/,"")} # Remove leading characters
str = arr.join("\n") # Rejoin into a single line
self.replace(str) # Replace contents of string
end
end
我想这个问题是:缺少可移植性/猴子补丁的存在会使这个解决方案变坏。
答案 5 :(得分:1)
出了什么问题:
code = "next line of code #{something}\n"+
"another line #{some_included_expression}"
答案 6 :(得分:0)
您可以将多行文本放在一个文件中,并使用ERB来解析它(注意ERB包含在Ruby中)
require 'erb'
multi_line_string = File.open("multi_line_string.erb", 'r').read
template = ERB.new(multi_line_string)
template.result(binding)
(ERB可以从Binding访问变量,Binding是一个提供对另一个对象拥有的实例方法和变量的访问的对象。通过将其设置为&#34;绑定&#34;它指向自身)
文档here。