Ruby | Array compact() operation

Array#compact () : compact () is a Array class method which returns the array after removing all the ‘nil’ value elements (if any) from the array.

Syntax:  Array.compact()

Parameter:  Array to remove the 'nil' value from. 

Return:  removes all the nil values from the array. 

Code #1 : Example for compact() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for compact() method
# showing how to remove nil values
  
# declaring array
a = [18, 22, 33, nil, 5, 6]
  
# declaring array
b = [5, 4, nil, 1, 88, 9]
  
# declaring array
c = [18, 22, nil, 40, 50, 6]
  
# removing nil value from array
puts "removing nil value : #{a.compact}\n\n"
  
# removing nil value from array
puts "removing nil value : #{b.compact}\n\n"
  
# removing nil value from array
puts "removing nil value : #{c.compact}\n\n"

chevron_right


Output :

removing nil value : [18, 22, 33, 5, 6]

removing nil value : [5, 4, 1, 88, 9]

removing nil value : [18, 22, 40, 50, 6]

Code #2 : Example for compact() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for compact() method
# showing how to remove nil values
  
# declaring array
a = ["abc", "nil", "dog"]
  
# declaring array
b = ["cow", nil, "dog"]
  
# declaring array
c = ["cat", nil, nil]
  
# removing nil value from array
puts "removing nil value : #{a.compact}\n\n"
  
# removing nil value from array
puts "removing nil value : #{b.compact}\n\n"
  
# removing nil value from array
puts "removing nil value : #{c.compact}\n\n"

chevron_right


Output :

removing nil value : ["abc", "nil", "dog"]

removing nil value : ["cow", "dog"]

removing nil value : ["cat"]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.