Ruby Hash compact!() 函数
compact!() 是一个Hash类方法,它在删除Hash中所有的 “nil “值元素(如果有的话)后返回Hash。如果Hash中没有nil值,则返回nil值。
语法。Hash.compact!()
参数:要删除 “nil “值的哈希值。
返回:从哈希中删除所有的nil值。
nil – 如果哈希中没有nil值的话。
例子 #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"
输出:
removing nil value : {a:100}
removing nil value : {a:100, b:200}
removing nil value : {}
例子#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"
输出:
removing nil value : {b:200}
removing nil value :
removing nil value : {a:100, b:200}