使用Ruby编程语言在程序中动态构建多行字符串

18

在编程时,我经常做的一件事情是:

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
7个回答

30
如果您想要构建一段文本,最简单的方法就是使用%运算符。例如:
code = %{First line
second line
Third line #{2 + 2}}
'

'code'将会如下所示

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

2
+1。另外,对于那些正在阅读此内容的人,您不需要使用%{string}...任何字符都可以。例如,%-string-或%string - kinofrost

18
这是一种方法:
code = []
code << "next line of code #{something}"
code << "another line #{some_included_expression}"
code.join("\n")

4
你可以不使用变量来拼接字符串: ["第一行", "第二行"].join("\n") - jaredjacobs

9

使用 <<- 运算符:

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

这看起来很不错(我猜这是一个 HERE 文档),但它保留了行首的空格。有没有什么方法可以去掉它? - Peter
代码 = <<-CODE.gsub(/^\s+/,'') 随后是通常的heredoc。 - glenn jackman
接近了,但我希望它也能保留缩进……只是额外的空格应该被去掉。是的,我知道有一个解决方法,但它很丑陋。 - Peter
为什么您要在HEREdoc中保留缩进呢?o0 - Eimantas

5

我想你可以直接在字符串中嵌入“...”来实现它。这里有一个有趣的方式:

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"

3

这里介绍了一种方法,点击此处查看详情:

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

我猜这个问题是:缺乏可移植性/存在猴子补丁是否使该解决方案不好。

不必为每一行都加上“|”前缀并更改String类,为什么不像我的答案那样使用“code << ”呢?您可以将“code”变量名称缩短为“d”。这很容易理解,任何Ruby程序员都应该能够弄清楚。 - Jim

1

What's wrong with:

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

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 是一个对象,提供对另一个对象拥有的实例方法和变量的访问权限。将其设置为 "binding",它就指向自身。

文档 在这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接