What is the opposite method of Array.empty? or [].empty? in ruby

Ruby

Ruby Problem Overview


I do realize that I can do

unless [1].empty? 

But I'm wondering if there is a method?

Ruby Solutions


Solution 1 - Ruby

As well as #any? as davidrac mentioned, with ActiveSupport there's #present? which acts more like a truth test in other languages. For nil, false, '', {}, [] and so on it returns false; for everything else true (including 0, interestingly).

Solution 2 - Ruby

You may use [1].any?, which is actually defined in Enumerable

Note that this will not work in case your array hold only nil or false values.

Solution 3 - Ruby

[nil].any?
=> false
[nil].any? {|something| true}
=> true
[].any? {|something| true}
=> false
[false, false].any? {|something| true}
=> true
[nil, 'g'].any? {|something| true}
=> true

Solution 4 - Ruby

No single method I know of is going to give you that in Ruby. Key word 'single':

[5].size.positive? => true
[5].size.nonzero? => 1

[].size.positive? => false
[].size.nonzero? => nil

Both of these are even more useful with the safe navigation operator, since nil returns falsy, meaning negative methods (like #empty?) break down a bit:

# nil considered 'not empty' isn't usually what you want
not_empty = proc{|obj| !obj&.empty? }

not_empty.call nil => true
not_empty.call [ ] => false
not_empty.call [5] => true


# gives different 3 answers for the 3 cases
# gives truthy/falsy values you'd probably expect
positive_size = proc{|obj| obj&.size&.positive? }

positive_size.call nil => nil
positive_size.call [ ] => false
positive_size.call [5] => true


# gives truthy/falsy values you'd probably expect
nonzero_size = proc{|obj| obj&.size&.nonzero? }

nonzero_size.call nil => nil
nonzero_size.call [ ] => nil
nonzero_size.call [5] => 1

Solution 5 - Ruby

To check for elements in array :
.empty?
.present?

if a={}
a.any? .nil?
will gives you false.

To check whether or not a field has a non-nil value:

.present?
.nil?
.any?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKamilski81View Question on Stackoverflow
Solution 1 - RubynoodlView Answer on Stackoverflow
Solution 2 - RubydavidracView Answer on Stackoverflow
Solution 3 - RubyRod McLaughlinView Answer on Stackoverflow
Solution 4 - RubyCRandERView Answer on Stackoverflow
Solution 5 - Rubyvidur punjView Answer on Stackoverflow