緊湊! ()是一種哈希類方法,該方法從哈希中刪除所有“ 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。