Swiss
Swiss

Reputation: 5829

Multiple Line String Formatting

Trying to format a mutliline string in Ruby

heredoc and %q{ } have the issue that they include whitespace used for formatting the code.

s = %q{Foo
         Bar
         Baz}
puts s

Incorrectly outputs the following:

Foo
          Bar
          Baz   

The following works, but is a bit ugly with the \ 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?

Upvotes: 3

Views: 860

Answers (3)

dbenhur
dbenhur

Reputation: 20408

A 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

Upvotes: 2

bta
bta

Reputation: 45057

You can always do something like this:

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

That way, you have quotation marks to explicitly demarcate the beginning and end of the strings, and the indentation whitespace is not mixed up with the strings.

Upvotes: 2

peter
peter

Reputation: 42182

build in allright but more by hazard than intended i suppose

s = %w{ Foo
        Bar
        Baz}

puts s

=> 
Foo
Bar
Baz

And if you want to keep the indentation of the first line, this one is surely build in by design

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

=>
        Foo
          Bar
          Baz

Upvotes: 3

Related Questions