Ruby clear() Method

Ruby clear() Function with Examples

Ruby clear() method is an array function that is used to remove all elements of an array and return an empty array. If the method is applied on an empty array then it also returns an empty array.

Applying this method on other data types excluding array, a compilation error will occur.

Syntax arr.clear()
Where arr is the array which elements should be cleared or removed.
Parameters This method does not take any parameters.
Return Value Return a NULL array. Means array without any elements []

Example Program:

arr1 = [1, 2, 3, 4, 5, 6, 7]
arr2 = ["a", "b", "c", "d", "e"]
arr3 = ["Lina", "Mohul", "Mehrab"]

# Raw clear without assigning into variable
puts "#{arr1}"

# Variable Assigning
A = arr2.clear
puts "#{arr2}"
puts "#{A}"
puts "#{arr3.clear()}"


Posted in