Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there an equivalent of Array#compact for empty elements?

Tags:

As we all know, Array#compact removes nil elements from the array.

array.reject { |element| element.empty? }

would remove empty elements like [] (in rails you could also do #blank? to get rid of empty elements and nil elements).

Is there a shorthand method for removing empty/blank elements like Array#compact? Or is using Array#reject my best bet?

I haven't seen the "empty" equivalent of #compact, if there is one. But maybe I'm just overlooking it.

like image 961
gregates Avatar asked Jun 20 '13 02:06

gregates


People also ask

What is the alternative of array?

I'd say T[] is the generic alternative of Array, except it existed before generics. how about arrays with reference type elements? you could have an object array or animal array.. That's just string[] or Animal[].

Can we use alternative of array?

T-SQL doesn't support arrays (groups of objects that have the same attributes and that you can use techniques such as subscripting to address individually). But you can use local or global temporary tables, which the main article describes, as an alternative to an array.

What is an alternative for array in C?

“Instead of adopting C variable-length arrays, we propose to define a new facility for arrays where the number of elements is bound at construction. We call these dynamic arrays, dynarray.

Can array have same values?

The areEqual function only returns true if the passed in arrays have the same length, their values are equal and in the same order. In this example, we call the areEqual function with two arrays containing the same elements in a different order and the function returns false .


1 Answers

Yes there is!

array.reject &:empty? 

However, as scarver2 and Hoang Le explained, this will fail with a NoMethodError if the array contains nil.


If you are using Rails or Active Support, you can safely write:

array.reject &:blank? 

There will be no error since all objects respond to blank?, including nil.

There is also another way to do it, as suggested by mu is too short:

array.select &:present? 

It seems present? is implemented in terms of blank? so both are appropriate.

like image 90
Matheus Moreira Avatar answered Sep 18 '22 06:09

Matheus Moreira