📜  红宝石 |哈希 compact()函数

📅  最后修改于: 2022-05-13 01:54:57.082000             🧑  作者: Mango

红宝石 |哈希 compact()函数

compact()是一个 Hash 类方法,它在从 Hash 中删除所有“nil”值元素(如果有)后返回 Hash。

示例 #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}