如何在Ruby中检查数组元素是否为空?

时间:2017-04-07 14:28:04

标签: ruby chef inspec

如何在Ruby中检查数组元素是否为空?

passwd.where { user =~ /.*/ }.uids
=> ["0",  "108",  "109",  "110",  "111",  "112",  "994",  "995",  "1001",  "1002",  "",  "65534"]

4 个答案:

答案 0 :(得分:0)

要检查数组是否有空元素,可以采用以下方法之一:

arr.any?(&:blank?)

答案 1 :(得分:0)

不确定你想用它做什么,但有很多方法可以给这只猫留下光泽。更多信息有助于缩小范围...

["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

答案 2 :(得分:0)

arr = [ "0",  "108",  "", [],  {},  nil, 2..1, 109, 3.2, :'' ]

arr.select { |e| e.respond_to?(:empty?) && e.empty? }
  #=> ["", [], {}, :""]

答案 3 :(得分:-1)

这些空虚测试:

public class ArrayLeftShift {
 public static void main(String[] args) {
  int[] myList = {95, -10, 23, -3, 78};

  System.out.print("myList: ");
  printArray(myList);

  leftShift(myList);
  System.out.print("After left shift: ");
  printArray(myList);    
}

public static void leftShift(int[] list) {
 int other = list[list.length+1];

for (int i = list.length+2; i >= 0; i++)
  list[i-1] = list[i];

list[0] = other;
System.out.print("\nshifted Array: ");
}

public static void printArray(int[] list) {
for (int d: list) 
  System.out.print(d + " ");
System.out.println();
}

}

测试以查看数组中的元素是否为空将使用类似的测试:

'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"]