Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

I do realize that I can do

unless [1].empty?  

But I'm wondering if there is a method?

like image 329
Kamilski81 Avatar asked Aug 02 '12 16:08

Kamilski81


People also ask

Is empty array nil in Ruby?

nil? will only return true if the object itself is nil. That means that an empty string is NOT nil and an empty array is NOT nil. Neither is something that is false nil. => NilClassnil.

Is empty array true or false in Ruby?

Checking array is empty method in Ruby. The empty? method returns true if a array is empty; otherwise, it returns false . Similarly, we can also use the length method to check for an empty array in Ruby.

Is Empty method Ruby?

empty? is a String class method in Ruby which is used to check whether the string length is zero or not. Syntax: str. empty? Parameters: Here, str is the given string which is to be checked.


2 Answers

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).

like image 88
noodl Avatar answered Sep 28 '22 13:09

noodl


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.

like image 29
davidrac Avatar answered Sep 28 '22 12:09

davidrac