1

How can I remove empty hash's from an array?

[{}, {}, :one, :two]

.compact does not seem to work.

1
  • 1
    [{}, {}, :one, :two] - [{}] is another way that hasn't been mentioned in the answers. Commented Sep 20, 2019 at 7:38

3 Answers 3

6

How can I remove empty hash's from an array?

Using reject, to reject elements in an enumerable by checking if the element is a Hash and is empty ({}):

p [{}, {}, :one, :two, [], [], '', nil].reject { |e| e == {} }
# [:one, :two, [], [], "", nil]
Sign up to request clarification or add additional context in comments.

3 Comments

+1 I was going to post recommending the use of select, until I saw your answer. I feel reject is much more readable than select with negative conditions in the block.
The best answer as it can handle whatever's thrown at it :)
@CarySwoveland That does appear more concise, doesn't it?
4

Delete empty hashes:

ar = [{}, {}, :one, :two]
ar.delete({})
p ar # => [:one, :two]

Comments

1

Try Array#reject unwanted elements:

ary = [{}, {}, :one, :two]
ary.reject! { |h| h.empty? }
ary
#=> [:one, :two]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.