String output function

2020-07-15 hit count image

Let's see how to use and what difference puts, print, and p.


In Ruby, puts, print, and p are String output functions. Let’s see what difference and how to use them.

puts function

In Ruby, puts is a basic output function. You can use it like below.

puts 'Hello World!'
# Hello World!

You can also use it with parentheses.

puts ('Hello World!')
# Hello World!

You can print multiple strings like below.

puts 'Hello', 'World!'
# Hello
# World!

The puts function prints the string and adds a line break at the last.

In Ruby, the print function is similar to puts function, but not add a line break.

print 'Hello World!'
# Hello World!

You can see a difference when you use it like below.

print 'Hello', ' World!'
# Hello World!

If you want to break a line, you should add the line break character(\n).

print "Hello\nWorld!"
# Hello
# World!

Note, when you use the Escape Sequences like the line break(\n) in Ruby, you should use the double quotation(") to print them well.

p function

In Ruby, you can print strings by itself via p function.

p '100'
# '100'

It is useful to distinguish numbers and strings like below.

p '100'
p 100
# '100'
# 100


We’ve seen what difference and how to use String Output Function in Ruby. There are many functions. Normally, puts is used, so just don’t forget puts function to print the string in Ruby.