Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the way to check if all the elements in an array are nil? [duplicate]

Tags:

arrays

ruby

I would like to know if there's anything except nil values in an array.

arr = [nil, nil, nil, nil] # => true
arr = [nil, 45, nil, nil] # => false

There could be any values of any types (not only 45).

like image 580
a-ta-ta Avatar asked Nov 29 '22 22:11

a-ta-ta


2 Answers

Use the Enumerable#all? method:

p arr.all? { |x| x.nil? }

Or

p arr.all?(&:nil?)

As @Stefan suggested,

 p arr.all?(NilClass) #works only for Ruby 2.5
like image 136
Rajagopalan Avatar answered Dec 25 '22 23:12

Rajagopalan


you could do arr.compact.empty?, compact gets rid of all the nil for you

you could read here at ruby guides to find about all the methods on Array class

like image 39
Subash Avatar answered Dec 25 '22 22:12

Subash