I'm looking for a more idiomatic way to filter out nil-or-empty elements of an array.
I have many methods of the form:
def joined [some_method, some_other_method].compact.reject(&:empty?).join(' - ') end
This will take the result of some_method
and some_other_method
and return only the one(s) that are both non-nil (compact
is essentially equivalent to reject(&:nil?)
) and non-empty.
Is there anything in Array or Enumerable that gets the same thing in one shot?
Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.
To check if a array is empty or not, we can use the built-in empty? method in Ruby. The empty? method returns true if a array is empty; otherwise, it returns false .
In Rails, you can do reject(&:blank?)
, or equivalently, select(&:present?)
.
If this is not for a Rails app, and you do this a lot, I'd advise you to define your own helper on String
or whatever else you are filtering.
class String alias :blank? :empty? end class NilClass def blank? true end 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