I want avoid iterating over a nil array.
My bad solution:
if nil!=myArr
myArr.each { |item|
p item;
}
end
Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.
The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.
each is just another method on an object. That means that if you want to iterate over an array with each , you're calling the each method on that array object. It takes a list as it's first argument and a block as the second argument.
In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.
For a simple one-liner, you might also use unless myArr.nil?
myArr.each { |item| p item } unless myArr.nil?
If you are comfortable with a nil
return rather than avoiding execution entirely, you can use the Safe navigation operator &.
. Note though that this differs slightly. Whereas the unless
version will skip execution entirely, the &.
will execute but return nil
.
myArr&.each { |item| p item }
# returns nil
In ruby, only nil
and false
are considered as false.
if myArr
myArr.each { |item|
p item
}
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With