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"]
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"]
To check if the array has an empty element, one of the many ways to do it is:
arr.any?(&:blank?)
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
arr = [ "0", "108", "", [], {}, nil, 2..1, 109, 3.2, :'' ]
arr.select { |e| e.respond_to?(:empty?) && e.empty? }
#=> ["", [], {}, :""]
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"
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"]