-4

How do you check if an array element is empty or not in Ruby?

passwd.where { user =~ /.*/ }.uids
=> ["0",  "108",  "109",  "110",  "111",  "112",  "994",  "995",  "1001",  "1002",  "",  "65534"]
Mark Wragg
  • 22,105
  • 7
  • 39
  • 68

5 Answers5

2

To check if the array has an empty element, one of the many ways to do it is:

arr.any?(&:blank?)
s1mpl3
  • 1,456
  • 1
  • 10
  • 14
0

Not sure what you want to do with it, but there are quite a few ways to skin this cat. More info would help narrow it down some...

["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
Derek Wright
  • 1,452
  • 9
  • 11
  • i need to check the index value of array which is empty and store it in a variable like below code checking userid in linux box. describe passwd.where { user =~ /.*/ }.uids do its("length") { should_not eq 0 } end – saravana kumar Apr 10 '17 at 09:04
0
arr = [ "0",  "108",  "", [],  {},  nil, 2..1, 109, 3.2, :'' ]

arr.select { |e| e.respond_to?(:empty?) && e.empty? }
  #=> ["", [], {}, :""]
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

Assuming your array is an array of strings

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

 if arr.empty?
   p "Array is empty"
 else
   p "Array has values inside"
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
-1

These test for emptiness:

'foo'.empty? # => false
''.empty? # => true

[1].empty? # => false
[].empty? # => true

{a:1}.empty? # => false
{}.empty? # => true

Testing to see if an element in an array is empty would use a similar test:

['foo', '', [], {}].select { |i| i.empty? }  # => ["", [], {}]
['foo', '', [], {}].reject { |i| i.empty? }  # => ["foo"]

or, using shorthand:

['foo', '', [], {}].select(&:empty?)  # => ["", [], {}]
['foo', '', [], {}].reject(&:empty?)  # => ["foo"]
the Tin Man
  • 158,662
  • 42
  • 215
  • 303