Open In App

Ruby | Hash compact!() function

Improve
Improve
Like Article
Like
Save
Share
Report

compact! () is a Hash class method which returns the Hash after removing all the ‘nil’ value elements (if any) from the Hash. If there are no nil values in the Hash it returns back the nil value.

Syntax: Hash.compact!()

Parameter: Hash to remove the ‘nil’ value from.

Return: removes all the nil values from the Hash.
nil – if there is no nil value in the Hash

Example #1 :




# Ruby code for compact!() method
# showing how to remove nil values
  
# declaring Hash value
a = {a:100, b:nil}
  
# declaring Hash value
b = {a:100, c:nil, b:200}
  
# declaring Hash value
c = {a:100}
  
  
# removing nil value from Hash
puts "removing nil value : #{a.compact!}\n\n"
  
# removing nil value from Hash
puts "removing nil value : #{b.compact!}\n\n"
  
# removing nil value from Hash
puts "removing nil value : #{c.compact!}\n\n"


Output :

removing nil value : {a:100}

removing nil value : {a:100, b:200}

removing nil value : {}

Example #2:




# Ruby code for compact!() method
# showing how to remove nil values
  
# declaring Hash value
a = { "a" => nil, "b" => 200 }
  
# declaring Hash value
b = {"a" => 100}
  
# declaring Hash value
c = {"a" => 100, "c" => nil, "b" => 200}
  
# removing nil value from Hash
puts "removing nil value : #{a.compact!}\n\n"
  
# removing nil value from Hash
puts "removing nil value : #{b.compact!}\n\n"
  
# removing nil value from Hash
puts "removing nil value : #{c.compact!}\n\n"


Output :

removing nil value : {b:200}

removing nil value : 

removing nil value : {a:100, b:200}


Last Updated : 07 Jan, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads