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