当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Hash compact()用法及代码示例


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}


相关用法


注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 Ruby | Hash compact() function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。