Ruby 数组 compact!() 操作
Array#compact!() : compact!() 是一个数组类的方法,在删除数组中所有的’nil’值元素(如果有的话)后返回数组。如果数组中没有nil值,则返回nil值。
语法。 Array.compact!()
参数。 要删除 “nil “值的数组。
返回:从数组中删除所有的nil值。 nil – 如果数组中没有nil值的话
代码#1: compact!()方法的例子
# Ruby code for compact!() method
# showing how to remove nil values
# declaring array
a = [18, 22, 33, nil, 5, 6]
# declaring array
b = [5, 4, 1, 88, 9]
# declaring array
c = [18, 22, nil, 40, 50, 6]
# removing nil value from array
puts "removing nil value : #{a.compact!}\n\n"
# removing nil value from array
puts "removing nil value : #{b.compact!}\n\n"
# removing nil value from array
puts "removing nil value : #{c.compact!}\n\n"
输出:
removing nil value : [18, 22, 33, 5, 6]
removing nil value :
removing nil value : [18, 22, 40, 50, 6]
代码#2: compact!()方法的例子
# Ruby code for compact!() method
# showing how to remove nil values
# declaring array
a = ["abc", "nil", "dog"]
# declaring array
b = ["cow", nil, "dog"]
# declaring array
c = ["cat", nil, nil]
# removing nil value from array
puts "removing nil value : #{a.compact!}\n\n"
# removing nil value from array
puts "removing nil value : #{b.compact!}\n\n"
# removing nil value from array
puts "removing nil value : #{c.compact!}\n\n"
输出:
removing nil value :
removing nil value : ["cow", "dog"]
removing nil value : ["cat"]