333

I have the following array

cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]

I want to remove blank elements from the array and want the following result:

cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

Is there any method like compact that will do it without loops?

1
  • 4
    Might be worth updating the accepted answer to @Marian13's answer now Rails 6 has compact_blank.
    – SRack
    May 27, 2022 at 10:00

21 Answers 21

554

There are many ways to do this, one is reject

noEmptyCities = cities.reject { |c| c.empty? }

You can also use reject!, which will modify cities in place. It will either return cities as its return value if it rejected something, or nil if no rejections are made. That can be a gotcha if you're not careful (thanks to ninja08 for pointing this out in the comments).

8
  • 246
    Or if you prefer more compact cities.reject!(&:empty?)
    – aNoble
    May 4, 2011 at 4:55
  • 57
    hm, why not cities.reject!(&:blank?)? empty? is for arrays
    – Nico
    Jul 17, 2012 at 20:35
  • 29
    @Nico blank? is only available through ActiveSupport. Standard Ruby does use String#empty?: ruby-doc.org/core-1.9.3/String.html#method-i-empty-3F Sep 10, 2012 at 15:00
  • 28
    reject is better than reject! because [].reject!(&:empty?) returns nil, [].reject(&:empty?) returns []
    – konyak
    Apr 29, 2015 at 18:06
  • 19
    watch out with reject!. reject! will return nil if no changes are made to the array. If you want to return the array when no changes have been made, just use reject without the bang.
    – Nick Res
    Aug 9, 2015 at 1:31
183
1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)

=> ["A", "B", "C"]
2
  • 14
    I would prefer to use .reject(&:blank?) to avoid nil values as well
    – ran632
    May 3, 2016 at 12:07
  • 7
    @RanGalili blank? is a good choice but its a rails method, and this question is regarding the plain ruby
    – Swaps
    Oct 22, 2016 at 5:49
113

Here is what works for me:

[1, "", 2, "hello", nil].reject(&:blank?)

output:

[1, 2, "hello"]
5
  • 1
    On Ruby 2.3.1 I get NoMethodError: "undefined method `blank?' for 1:Fixnum" trying to execute this.
    – Tom
    Feb 6, 2019 at 19:43
  • 1
    @Tom blank? is a Rails specific method. Doesn't exist on Array for plain ruby. You will have to use empty? or write your own method.
    – jpgeek
    Feb 7, 2019 at 6:09
  • @jpgeek Thanks for the clarification, that was the trouble I was having in realizing :blank? is Rails-specific.
    – Tom
    Feb 7, 2019 at 16:17
  • Because NoMethodError: undefined method empty? for nil:NilClass , :blank? is better than :empty?
    – Lane
    Dec 9, 2019 at 1:34
  • :blank works better than :empty. Because :empty does not work for nil
    – KBIIX
    Dec 16, 2019 at 11:52
57

In my project I use delete:

cities.delete("")
2
  • 6
    elegant! unfortunately doesn't return the remaining array, but pretty slick
    – Kevin
    Nov 3, 2012 at 20:37
  • 12
    The Array.delete is counter-intuitive. It operates like a .delete!() if such a method existed. The .delete() operates directly on the array in a destructive manner.
    – scarver2
    Jul 10, 2013 at 20:36
47

compact_blank (Rails 6.1+)

If you are using Rails (or a standalone ActiveSupport), starting from version 6.1, there is a compact_blank method that removes blank values from arrays.

It uses Object#blank? under the hood for determining if an item is blank.

["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"].compact_blank
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

[1, "", nil, 2, " ", [], {}, false, true].compact_blank
# => [1, 2, true]

Here is a link to the docs and a link to the relative PR.

A destructive variant is also available. See Array#compact_blank!.


If you have an older version of Rails, check compact_blank internal implementation.

It is not so complex to backport it.

def compact_blank
  reject(&:blank?)
end

If you need to remove only nil values, consider using Ruby build-in Array#compact and Array#compact! methods.

["a", nil, "b", nil, "c", nil].compact
# => ["a", "b", "c"]
46

When I want to tidy up an array like this I use:

["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - ["", nil]

This will remove all blank or nil elements.

1
  • 1
    Actually, The Tin Man's answer is better as it will also remove anything which matches Object#blank? i.e. nil, "", "\n", " ", "\n\r", etc. Unlike the accepted answer, it will also work without Rails. Sep 23, 2013 at 8:34
29

Most Explicit

cities.delete_if(&:blank?)

This will remove both nil values and empty string ("") values.

For example:

cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal", nil]

cities.delete_if(&:blank?)
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
5
  • Removing punctuation and adding a colon gives "Cities: delete if blank" :D
    – clapp
    Dec 19, 2015 at 0:25
  • 2
    blank is a ruby or rails method?
    – Arnold Roa
    Dec 29, 2015 at 15:33
  • 2
    @ArnoldRoa It is a Rails method.
    – PaulMest
    Feb 8, 2016 at 5:30
  • 1
    what if there is a space between the empty string? Aug 3, 2017 at 5:21
  • @StevenAguilar a space is considered as length 1 (because a space is a character). " ".blank? => false
    – phlegx
    Aug 4, 2017 at 6:50
23

Try this:

puts ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - [""]
5
  • 4
    This is slick, and doesn't return ""! This is a great lil trick. Jun 17, 2013 at 18:45
  • 2
    ["Kathmandu", "Pokhara", " ", "Dharan", "Butwal"] - [""] - will not work in this case
    – ajahongir
    Oct 29, 2014 at 7:53
  • 2.0.0-p247 :001 > ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - [""] => ["Kathmandu", "Pokhara", "Dharan", "Butwal"] Seems to work for me. Why do you think it doesn't work?
    – Raels
    Oct 30, 2014 at 1:07
  • 1
    @Raels, the blank string in this case is not empty. It has a single space within it. Nov 13, 2014 at 6:40
  • 1
    @Chandranshu I beg to differ. I copied and pasted the text into an editor and found there was no space between the quotes as you suggested. If there was, then subtracting ["", " "] would work. superluminary's example is similar and works as well. The original request was to remove "blank elements" not "elements that are blanks", and the example blank element was shown in the OP as "".
    – Raels
    Nov 15, 2014 at 1:08
20

Use reject:

>> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
9
  • 14
    Or, as aNoble noted above, reject(&:empty?). May 4, 2011 at 5:00
  • Symbol to proc is slower in 1.8.7 than the block format. It is on par from what i've seen in 1.9.2 May 4, 2011 at 15:35
  • This is good as it will remove any element which matches Object#empty?, eg. "\n", " ", nil, "\n\n\n", etc... Oct 7, 2013 at 14:46
  • 5
    nil.empty? booom break!
    – Naveed
    Jan 15, 2014 at 17:35
  • 1
    @AllenMaxwell @Naveed If your array has nil elements, precede the reject(&:empty?) with compact e.g. [nil, ''].compact.reject(&:empty?)
    – scarver2
    Jan 21, 2015 at 19:45
14
cities.reject! { |c| c.blank? }

The reason you want to use blank? over empty? is that blank recognizes nil, empty strings, and white space. For example:

cities = ["Kathmandu", "Pokhara", " ", nil, "", "Dharan", "Butwal"].reject { |c| c.blank? }

would still return:

["Kathmandu", "Pokhara", "Dharan", "Butwal"]

And calling empty? on " " will return false, which you probably want to be true.

Note: blank? is only accessible through Rails, Ruby only supports empty?.

12

There are already a lot of answers but here is another approach if you're in the Rails world:

 cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?
2
  • 4
    present? comes from ActiveSupport. This has a no Rails tag and requiring an extra gem for one method seems excessive. Sep 10, 2012 at 14:59
  • 1
    @Naveed, you should preface this with "If you're using RoR". I won't downvote it because it's still useful information for beginners.
    – pixelearth
    Jul 4, 2013 at 0:28
10

Here is one more approach to achieve this

we can use presence with select

cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"]

cities.select(&:presence)

["Kathmandu", "Pokhara", "Dharan", "Butwal"]
1
  • 2
    Thank you for this. I had some " " elements in my array that were not removed with the reject method. Your method removed nil "" or " " items.
    – iamse7en
    Oct 16, 2015 at 0:39
10

To remove nil values do:

 ['a', nil, 'b'].compact  ## o/p =>  ["a", "b"]

To remove empty strings:

   ['a', 'b', ''].select{ |a| !a.empty? } ## o/p => ["a", "b"]

To remove both nil and empty strings:

['a', nil, 'b', ''].select{ |a| a.present? }  ## o/p => ["a", "b"]
1
  • 5
    ['a', nil, 'b', ''].select(&:present?) for shorthand Sep 26, 2020 at 0:23
8

Here is a solution if you have mixed types in your array:

[nil,"some string here","",4,3,2]

Solution:

[nil,"some string here","",4,3,2].compact.reject{|r| r.empty? if r.class == String}

Output:

=> ["some string here", 4, 3, 2]
5

You can Try this

 cities.reject!(&:empty?)
1
  • 3
    maybe u meant cities.reject!(&:blank?)
    – xguox
    Jul 11, 2014 at 6:21
2
 cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? } 
1
  • delete and arranging would be a costly operation
    – Naveed
    Sep 10, 2012 at 14:23
2

Shortest way cities.select(&:present?)

1

Update in reject and reject!

NOTE: I came across this question and checked these methods on the irb console with ruby-3.0.1. I also checked the ruby docs but this is not mentioned there. I am not sure from which ruby version this change is there. Any help from the community is much appreciated.

With ruby-3.0.1 we can use either reject or reject!

cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

or shorthand

cities.reject(&:empty?)
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

both will return [] no matter we have an empty value or not?

enter image description here

0

another method:

> ["a","b","c","","","f","g"].keep_if{|some| some.present?}
=> ["a","b","c","f","g"]
0

Plain Ruby:

values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
puts values # [1,2,3]
-3

Update with a strict with join & split

cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.join(' ').split

Result will be:

["Kathmandu", "Pokhara", "Dharan", "Butwal"]

Note that: this doesn't work with a city with spaces

2
  • 2
    Looks very risky!
    – msdundar
    Jun 17, 2017 at 1:19
  • 1
    This will definitely fail if you have city like "New York" or "Naujoji Akmene" :)
    – Petras L
    Mar 5, 2020 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.