How to Remove an Element From an Empty Array in Ruby
An array is like a variable that stores multiple values, rather than one. Arrays can contain a mixture of elements; for example, "a = [1, 'two', 3.0]" is just as valid as "a = [1, 2, 3]". An empty array is an array that contains no elements, such as "a = [ ]". Ruby has two methods you can utilize to create an empty array; one method removes all of the elements from an array at once, while the other removes a single element from the array.
Instructions
-
-
1
Input "array.empty?" to check if the array contains elements. If the program returns "true," the array contains no elements to remove.
-
2
Insert "arrayname.clear" into the code or into Interactive Ruby (IRB) to remove all elements from an array. Replace "arrayname" with the name of the desired array.
-
-
3
Insert "a.delete_at(#)" to remove a single element from an array. Ruby starts at "0" when numbering elements in an array. For example,
a = [1, 2, 3]
a.delete_at(0)the above code would remove "1" from the array, changing the array to "a = [2, 3]". Using "a.delete_at(0)" a second time would remove "2" from the array.
-
4
Repeat step three until all elements are removed, creating an empty array. You can create a simple loop statement in the program to remove all arrays if you don't want to use the "clear" method:
while a.empty? == false
a.delete_at(0)
end
-
1
References
- Ruby: Visual Quickstart Guide; Larry Ullman; 2008
- Ruby-Doc.org: Class: Array