Ruby | Array compact!() operation
Last Updated :
08 Jan, 2020
Array#compact! () : compact! () is a Array class method which returns the array after removing all the ‘nil’ value elements (if any) from the array. If there are no nil values in the array it returns back the nil value.
Syntax: Array.compact!()
Parameter: Array to remove the 'nil' value from.
Return: removes all the nil values from the array. nil - if there is no nil value in the array
Code #1 : Example for compact!() method
a = [ 18 , 22 , 33 , nil , 5 , 6 ]
b = [ 5 , 4 , 1 , 88 , 9 ]
c = [ 18 , 22 , nil , 40 , 50 , 6 ]
puts "removing nil value : #{a.compact!}\n\n"
puts "removing nil value : #{b.compact!}\n\n"
puts "removing nil value : #{c.compact!}\n\n"
|
Output :
removing nil value : [18, 22, 33, 5, 6]
removing nil value :
removing nil value : [18, 22, 40, 50, 6]
Code #2 : Example for compact!() method
a = [ "abc" , "nil" , "dog" ]
b = [ "cow" , nil , "dog" ]
c = [ "cat" , nil , nil ]
puts "removing nil value : #{a.compact!}\n\n"
puts "removing nil value : #{b.compact!}\n\n"
puts "removing nil value : #{c.compact!}\n\n"
|
Output :
removing nil value :
removing nil value : ["cow", "dog"]
removing nil value : ["cat"]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...