How do I check if there's a nil set or not in an array?
any?
iterates over a container, like an array, and looks at each element passed to it to see if it passes a test. If one does, the loop stops and true
is returned:
ary = [nil, 1]
ary.any?{ |e| e.nil? } # => true
The documentation explains this well:
Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } that will cause any? to return true if at least one of the collection members is not false or nil.
%w[ant bear cat].any? { |word| word.length >= 3 } #=> true
%w[ant bear cat].any? { |word| word.length >= 4 } #=> true
[nil, true, 99].any? #=> true
any?
is one of a number of tests that can be applied to an array to determine if there are none?
, any?
, one?
, or all?
.
ary.one?{ |e| e == 1 } # => true
ary.none?{ |e| e == 2 } # => true
ary.all? { |e| e.nil? } # => false
Your code fails because you're trying to use a non-existing any?
method for a nil value, hence the error you got: "NoMethodError: undefined method `any?' for nil:NilClass"
ary[0] # => nil
ary.first # => nil
ary.first.respond_to?(:'any?') # => false
You have to pay attention to what you're doing. ary[0]
or array.first
returns the element at that array index, not an array.
empty?
only checks to see if the container has elements in it. In other words, does it have a size > 0?
ary.empty? # => false
ary.size == 0 # => false
ary.size > 0 # => true
[].empty? # => true
[].size == 0 # => true
[].size > 0 # => false
What's the way to check if all the elements in an array are nil?
You can also use #any? method for array
[nil, 45].any?
=> true
[nil, nil].any?
=> false
From the documentation:
If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil.
Note: This won't work if false
boolean values are present.
[nil, false].any?
=> false # It should return `true`
Other options would be:
arr = [nil, nil, 45]
arr.count(nil) == arr.length
=> false
(arr - [nil]).empty?
=> false
ruby array checking for nil array
[""]
is an array with a single element containing an empty String object. [].empty?
will return true
. @a.nil?
is returning false
because @a
is an Array object, not nil
.
Examples:
"".nil? # => false
[].nil? # => false
[""].empty? # => false
[].empty? # => true
[""].all? {|x| x.nil?} # => false
[].all? {|x| x.nil?} # => true
[].all? {|x| x.is_a? Float} # => true
# An even more Rubyish solution
[].all? &:nil? # => true
That last line demonstrates that [].all?
will always return true, because if an Array is empty then by definition all of its elements (no elements) fulfill every condition.
How to check if array is empty or does not exist?
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array does not exist or is empty
}
Update
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ⇒ do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values likenull
,undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as thearguments
object and DOMNodeList
objects. Depending on your situation, this might not be the behavior you're after.The
array.length
condition checks whether the variable'slength
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons likearray.length != 0
orarray.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}
array.nil? when array having only multiple `nil` values
You can use Array#any?
to check if the array contains at least one value that is not false
or nil
:
array = [1,2] unless array.any?
If array
is allowed to contain false
and you are interested only in nil
then Array#any?
needs a block:
array = [1,2] unless array.any?{|i| !i.nil?}
Update
As @mu-is-too-short suggests, a better version is:
array = [1,2] if array.all?(&:nil?)
It does exactly what you need: Enumerable#all? returns true
if the block returns a true-ish value for all elements of the array.
How to check if an array is empty or exists?
if (typeof image_array !== 'undefined' && image_array.length > 0) {
// the array is defined and has at least one element
}
Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var
whenever declaring a variable:
<?php echo "var image_array = ".json_encode($images);?>
// add var ^^^ here
And then make sure you never accidently redeclare that variable later:
else {
...
image_array = []; // no var here
}
How to check whether an array is empty using PHP?
If you just need to check if there are ANY elements in the array, you can use either the array itself, due to PHP's loose typing, or - if you prefer a stricter approach - use count()
:
if (!$playerlist) {
// list is empty.
}
if (count($playerlist) === 0) {
// list is empty.
}
If you need to clean out empty values before checking (generally done to prevent explode
ing weird strings):
foreach ($playerlist as $key => $value) {
if (!strlen($value)) {
unset($playerlist[$key]);
}
}
if (!$playerlist) {
//empty array
}
Related Topics
How to Organize Minitest/Unit Tests
Is Alias_Method_Chain Synonymous with Alias_Method
Using Multiple Controllers in One View in Rails
How to Find a Model's Relationships
How to Setup Urls for Static Site with Ruby Rack on Heroku
Set the Display Precision of a Float in Ruby
Clarification on the Ruby << Operator
Error Occurred While Installing Mini_Racer (0.2.0)
Rendering Haml Partials from Within Haml Outside of Rails
Ruby: How to Group a Ruby Array
How to Include a Yaml File Inside a Yaml File in Ruby
Rails Implementation of Search with Autocomplete
Share Models Between 2 Rails API's (Separate Applications)
Using Ruby, Reading a File, Containing Name/Value Pairs into a Hash
Why Is Ruby's Date Class Automatically Loaded But Datetime Is Not