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