Array#compact():compact()是Array类的一种方法,该方法会在从数组中删除所有“ nil”个值元素(如果有)后返回数组。
用法: Array.compact() 参数: Array to remove the 'nil' value from. 返回: removes all the nil values from the array.
代码#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, nil, 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:[5, 4, 1, 88, 9] 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:["abc", "nil", "dog"] removing nil value:["cow", "dog"] removing nil value:["cat"]
相关用法
- Ruby Array compact!()用法及代码示例
- Ruby Array map!()用法及代码示例
- Ruby Array at()用法及代码示例
- Ruby Array dig()用法及代码示例
- Ruby Array any?()用法及代码示例
- Ruby Array size()用法及代码示例
- Ruby Array class eql?()用法及代码示例
- Ruby Array concat()用法及代码示例
- Ruby Array intersection用法及代码示例
- Ruby Array bsearch()用法及代码示例
- Ruby Array count()用法及代码示例
- Ruby Array collect!()用法及代码示例
- Ruby Array clear()用法及代码示例
- Ruby Array collect()用法及代码示例
- Ruby Array bsearch_index()用法及代码示例
注:本文由纯净天空筛选整理自mayank5326大神的英文原创作品 Ruby | Array compact() operation。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。