Steven Jones
Steven Jones

Reputation: 99

Ruby newline use of two \n

I have a question about the need for the use of \n\n to make a newline. Please see below examples.

If I do ..

puts "hello"
puts "hi"

or

puts "hello\n"
puts "hi"

The output is..

hello  
hi

If I do ..

puts "hello\n\n"
puts "hi"

The output is..

hello

hi

Why do I need \n\n to make one extra newline?
Why doesn't the single \n make any difference?

Upvotes: 2

Views: 257

Answers (3)

David Hempy
David Hempy

Reputation: 6237

The other answers here nailed it.

If you want to avoid the magic handling of \n, try using print instead of puts. print outputs your string literally, with no line ending unless you put it there.

> 3.times { print 'Zap' }
ZapZapZap=> 3
> 3.times { puts 'Zap' }
Zap
Zap
Zap
=> 3

Upvotes: 0

sawa
sawa

Reputation: 168101

The purpose of puts is to ensure the string ends with the newline character.

  • If there is none, then one newline character will be appended.
  • If there is one or more, no newline character will be appended.

Upvotes: 2

August
August

Reputation: 12558

From the documentation:

puts(obj, ...) → nil

Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.

Upvotes: 3

Related Questions