Search code examples
rubyputs

Preferred style for displaying multiple lines using `puts`


I know there are several different ways of being able to combine puts statements into one. But more importantly, I'm trying to determine if there's a generally accepted/preferred style for this (I've only been able to dig up other people's clever ways of doing it, but no real reference on a preferred style).

I've seen things like this:

puts "This", "is", "fairly", "easy"  # Each word goes on it's own line

or perhaps:

puts ["This", "seems", "convoluted"].join("\n") # Each word goes on it's own line

or an "ugly" way:

  def ugly_puts
    puts "Not using quotes
And using no code indentation to preserve output formatting"
  end

or simply:

puts "This"
puts "Seems" 
puts "Straightforward."

It makes most sense for me to use the last methodology, but I'm just curious if there's a common/preferred way I should go about dealing with multiple line output like this.


Solution

  • If the lines to be printed are short enough to be put together on a single line in the source, then I would go with your first option:

    puts "This", "is", "fairly", "easy"
    

    If they are long, then I would use a heredoc:

    puts <<_.unindent
      This Blah Blah ...
      Seems Blah Blah ...
      Straightforward. Blah Blah ...
    _
    

    where unindent is a method to unindent an indented heredoc along the lines suggested in Ruby indented multiline strings. Notice that in future versions of Ruby, it is likely that there will be a simpler way to unindent a heredoc, so this option will become more useful.

    I see no point in using your second or fourth option. The third may be used, but it looks ugly.