3

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?

1
  • You should use textwrap.dedent as the equivalent Python example, because the Ruby snippet is hardly more complicated than your Python snippet. You should also make it clear that your not interested in non-builtin methods. Commented Apr 11, 2012 at 20:21

3 Answers 3

3

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 
Sign up to request clarification or add additional context in comments.

4 Comments

It's probably better to call join("\n") on that first one, lest it only work as expected when called with puts.
yeah, i considered doing so but the beauty of this solution is the simplicity and if you use other print methods you can always add it like eg print s.join("\n") You can also use p s to have the array look and if course it IS an array what in some cases suites fine. Moreover, the more you add the less build it is isn't it ? Thans for the suggestion Andrew
Except the OP is asking for a string, not an array.
Andrew, its starts as a string, gets arrayed and is presented like a string, if not good enough look at my second solution which best answers the OP's question
2

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 

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.