-4

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

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

5 回答 5

2

要检查数组是否有空元素,执行此操作的众多方法之一是:

arr.any?(&:blank?)
于 2017-04-07T15:05:26.457 回答
0
arr = [ "0",  "108",  "", [],  {},  nil, 2..1, 109, 3.2, :'' ]

arr.select { |e| e.respond_to?(:empty?) && e.empty? }
  #=> ["", [], {}, :""]
于 2017-04-10T03:09:34.293 回答
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
于 2017-04-07T18:27:02.550 回答
0

假设您的数组是一个字符串数组

 arr = [ "name",  "address",  "phone", "city",  "country",  "occupation"]

 if arr.empty?
   p "Array is empty"
 else
   p "Array has values inside"
于 2021-10-11T13:42:12.780 回答
-1

这些测试空虚:

'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"]
于 2017-04-07T19:15:34.517 回答