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.
array.clear()
The clear()
method does not accept any parameters.
The clear()
method returns an empty array when called on an array.
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 arraysarr1 = [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 arraysa = arr1.clear()b = arr2.clear()c = arr3.clear()d = arr4.clear()e = arr5.clear()# log returned values to console# Empty arraysputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"puts "#{e}"