簡體   English   中英

在Ruby中以編程方式構建多行字符串

[英]Building multi-line strings, programmatically, in Ruby

這是我在編程時經常做的事情:

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

如果您正在構建一個文本塊,那么簡單的方法就是使用%運算符。 例如:

code = %{First line
second line
Third line #{2 + 2}}

那么'代碼'將是

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

這將是一種方式:

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

使用<< - 運算符:

code = <<-CODE
var1 = "foo"
var2 = "bar"
CODE

我想你可以在你的琴弦中嵌入...... \\ 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"

這里的介紹的方法在這里

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

我想這個問題是:缺少可移植性/猴子補丁的存在會使這個解決方案變壞。

有什么不對:

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

您可以將多行文本放在一個文件中,並使用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是一個提供對另一個對象擁有的實例方法和變量的訪問的對象。通過將其設置為“binding”,它指向自身)

文檔在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM