String output function

2024-09-25 hit count image

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

Outline

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

Completed

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.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts