代码之家  ›  专栏  ›  技术社区  ›  Peter

用Ruby以编程方式生成多行字符串

  •  16
  • Peter  · 技术社区  · 15 年前

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

    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 回复  |  直到 7 年前
        1
  •  17
  •   Jim    15 年前

    这是一种方法:

    code = []
    code << "next line of code #{something}"
    code << "another line #{some_included_expression}"
    code.join("\n")
    
        2
  •  27
  •   Harpastum    15 年前

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

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

    “代码”将是

    "First line\n second line\n Third line 4"
    
        3
  •  9
  •   Eimantas    15 年前

    使用<<-运算符:

    code = <<-CODE
    var1 = "foo"
    var2 = "bar"
    CODE
    
        4
  •  5
  •   DigitalRoss    8 年前

    我想,你只要把……嵌入你的弦中就行了。以下是一个有趣的方法:

    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"
    
        5
  •  3
  •   Peter    15 年前

    这里介绍了一种方法 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
    

    我想问题是:缺少可移植性/猴子补丁的存在是否会使这个解决方案变得糟糕?

        6
  •  1
  •   jjnevis    9 年前

    怎么了:

    code = "next line of code #{something}\n"+
           "another line #{some_included_expression}"
    
        7
  •  0
  •   dangerousdave    10 年前

    您可以将多行文本放在一个文件中,并使用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可以从绑定访问变量,这个对象提供对实例方法的访问,以及由另一个对象拥有的变量。通过将其设置为“绑定”,它指向自身)

    文档 here .