What is array.clear() in Ruby?

Overview

The clear() method in Ruby is used to clear or remove all the elements in an array. This is a simple method in Ruby that is very easy to use and understand.

Syntax

array.clear()

Parameters

The clear() method does not accept any parameters.

Return value

The clear() method returns an empty array when called on an array.

Code

In the code example below, several arrays are created. One by one, we call the clear() method on them, and what is left of the arrays is logged to the console.

# create arrays
arr1 = [1, 2, 3, 4, 5]
arr2 = ["a", "b", "c", "d", "e"]
arr3 = ["Ruby", "Java", "JavaScript", "Python"]
arr4 = ["1ab", "2cd", "3ef", "4gh", "5ij"]
arr5 = [nil, "nil", "true", "false", true]
# call the clear() method on the arrays
a = arr1.clear()
b = arr2.clear()
c = arr3.clear()
d = arr4.clear()
e = arr5.clear()
# log returned values to console
# Empty arrays
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources