puts in Ruby



In this tutorial, we will learn about the 'puts' method in Ruby. We will cover the basics of using 'puts' to output data to the console.


What is 'puts'

The 'puts' method in Ruby is used to print output to the console. It adds a newline after each argument.


Syntax

The syntax to use 'puts' in Ruby is:

puts object


Example 1: Printing a string using puts

We can use puts method to print a string.

For example,

  1. Declare a string variable named greeting.
  2. Assign the value 'Hello, World!' to the variable.
  3. Use puts to print the value of the variable.

Ruby Program

greeting = 'Hello, World!'
# Print the value of the variable
puts greeting

Output

Hello, World!


Example 2: Printing multiple lines using puts

We can print a multiline string using puts method.

For example,

  1. Use puts to print the first line.
  2. Use puts to print the second line.
  3. Observe that each line is printed on a new line.

Ruby Program

puts 'First line'
puts 'Second line'

Output

First line
Second line


Example 3: Printing an array using puts

We can print the elements of an array to output using puts method.

For example,

  1. Declare an array variable named fruits.
  2. Assign the value ['Apple', 'Banana', 'Cherry'] to the variable.
  3. Use puts to print each element of the array.

Ruby Program

fruits = ['Apple', 'Banana', 'Cherry']
# Print each element of the array
puts fruits

Output

Apple
Banana
Cherry