Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.clear() in Ruby?

okwudili onyejiaku

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}"

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring