Formatting multiple lines

Trying to format mutliline string in Ruby

heredocand %q{ }there is a problem that they include spaces used to format the code.

s = %q{Foo
         Bar
         Baz}
puts s

Incorrectly produces the following:

Foo
          Bar
          Baz   

The following works, but a little ugly with characters \.

s = "Foo\n" \
    "  Bar\n" \
    "  Baz"
puts s

The following works in python:

s = ("Foo\n"
     "  Bar\n"
     "  Baz")
print s

Is there an equivalent in Ruby?

+3
source share
3 answers

The trick I stole from The Ruby Way :

class String
  def heredoc(prefix='|')
    gsub /^\s*#{Regexp.quote(prefix)}/m, ''
  end
end

s = <<-END.heredoc
    |Foo
    |  Bar
    |  Baz
    END
+2
source

to build everything in order, but more dangerous than expected.

s = %w{ Foo
        Bar
        Baz}

puts s

=> 
Foo
Bar
Baz

And if you want to keep the indentation in the first line, it will certainly be built by design

s   = <<-END
        Foo
          Bar
          Baz
      END
puts s

=>
        Foo
          Bar
          Baz
+3
source

- :

s = ["Foo",
     "  Bar",
     "  Baz"].join("\n")
puts s
=>
Foo
  Bar
  Baz

, , , .

+2

All Articles