compact()是一种Hash类方法,在从Hash中删除所有“ nil”个值元素(如果有)后,将返回Hash。
用法:Hash.compact()
参数:散列可删除其中的“零”值。
返回:从哈希中删除所有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}
相关用法
- Ruby Hash compact!()用法及代码示例
- Ruby Hash each()用法及代码示例
- Ruby Hash key()用法及代码示例
- Ruby Hash key?()用法及代码示例
- Ruby Hash eql?用法及代码示例
- Ruby Hash dig()用法及代码示例
- Ruby Hash any?()用法及代码示例
- Ruby Hash clear()用法及代码示例
- Ruby Hash each_pair()用法及代码示例
- Ruby Hash each_key()用法及代码示例
- Ruby Hash invert()用法及代码示例
- Ruby Hash to_s()用法及代码示例
- Ruby Vector hash()用法及代码示例
- Ruby Hash each_key用法及代码示例
- Ruby Hash delete_if()用法及代码示例
注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 Ruby | Hash compact() function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。