📜  红宝石 |哈希压缩!()函数

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

红宝石 |哈希压缩!()函数

袖珍的! ()是一个 Hash 类方法,它在从 Hash 中删除所有“nil”值元素(如果有)后返回 Hash。如果 Hash 中没有 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}