如何在 Ruby 中检查数组元素是否为空?
passwd.where { user =~ /.*/ }.uids
=> ["0", "108", "109", "110", "111", "112", "994", "995", "1001", "1002", "", "65534"]
如何在 Ruby 中检查数组元素是否为空?
passwd.where { user =~ /.*/ }.uids
=> ["0", "108", "109", "110", "111", "112", "994", "995", "1001", "1002", "", "65534"]
要检查数组是否有空元素,执行此操作的众多方法之一是:
arr.any?(&:blank?)
arr = [ "0", "108", "", [], {}, nil, 2..1, 109, 3.2, :'' ]
arr.select { |e| e.respond_to?(:empty?) && e.empty? }
#=> ["", [], {}, :""]
不知道你想用它做什么,但有很多方法可以给这只猫剥皮。更多信息将有助于缩小范围...
["0", "108", "109", "110", "111", "112", "994", "995", "1001", "1002", "", "65534"].map { |v| v.empty? }
=> [false, false, false, false, false, false, false, false, false, false, true, false]
["0", "108", "109", "110", "111", "112", "994", "995", "1001", "1002", "", "65534"].each_with_index { |v,i| puts i if v.empty? }
10
假设您的数组是一个字符串数组
arr = [ "name", "address", "phone", "city", "country", "occupation"]
if arr.empty?
p "Array is empty"
else
p "Array has values inside"
这些测试空虚:
'foo'.empty? # => false
''.empty? # => true
[1].empty? # => false
[].empty? # => true
{a:1}.empty? # => false
{}.empty? # => true
测试数组中的元素是否为空将使用类似的测试:
['foo', '', [], {}].select { |i| i.empty? } # => ["", [], {}]
['foo', '', [], {}].reject { |i| i.empty? } # => ["foo"]
或者,使用速记:
['foo', '', [], {}].select(&:empty?) # => ["", [], {}]
['foo', '', [], {}].reject(&:empty?) # => ["foo"]