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.
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[].
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.
“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.
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 .
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.
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