Q:

Ruby program to remove all \'nil\' elements from the array

belongs to collection: Ruby Arrays Programs

0

In this program, we will create an array of integer elements. Then we will remove all "nil" elements from the array using the compact() method.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to remove all "nil" elements from the array is given below. The given program is compiled and executed successfully.

# Ruby program to remove all 
# "nil" elements from the array

arr = [10,21,30,nil,41,nil,50];

print "Array elements: \n",arr,"\n";

arr = arr.compact();

print "Array elements: \n",arr,"\n";

Output:

Array elements: 
[10, 21, 30, nil, 41, nil, 50]
Array elements: 
[10, 21, 30, 41, 50]

Explanation:

In the above program, we created an array arr with some elements. Then we removed all "nil" elements from the array using the compact() method. After that, we printed the updated array.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby Arrays Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Ruby program to check an array is empty or not... >>
<< Ruby program to remove all elements from the array...