To print with a newline in Ruby, we simply need to use the puts command instead of print. Let’s take a look at each below.

Here is how the puts command works.

number_one = "one"
number_two = "two"
number_three = "three"
number_four = "four"
number_five = "five"

puts number_one
puts number_two
puts number_three
puts number_four
puts number_five

#Output
one
two
three
four
five

Let’s see how this example would work if we used the print command.

number_one = "one"
number_two = "two"
number_three = "three"
number_four = "four"
number_five = "five"

print number_one
print number_two
print number_three
print number_four
print number_five

#Output
onetwothreefourfive

So as you can see, the puts command will return a newline after it prints, while the print command will print without a newline after it.

Let’s look at another way to print with a newline in Ruby.

Using “n” to Print Newline in Ruby

We can also use "n" to return a new line. So let’s take our print example from above, and use the newline code "n" to get a newline between each print.

number_one = "one"
number_two = "two"
number_three = "three"
number_four = "four"
number_five = "five"

print number_one + "n"
print number_two + "n"
print number_three + "n"
print number_four + "n"
print number_five + "n"

#Output
one
two
three
four
five

Hopefully this article has been helpful for you to learn how to use Ruby to print with newline.

Categorized in:

Ruby,

Last Update: March 4, 2024