Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Ruby filter for nil-or-empty?

Tags:

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?

like image 441
benizi Avatar asked Nov 21 '12 18:11

benizi


People also ask

Is nil or empty Ruby?

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.

How do you check if an object is nil in Ruby?

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

How do you get rid of nil in Ruby?

Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.

How do you check if an array is nil in Ruby?

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 .


1 Answers

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 
like image 54
Alex D Avatar answered Oct 27 '22 00:10

Alex D