0

I have an element in my array that when I print out the value of that specific element I get an empty value.

puts my_listing[2].inspect
[]

When I check to see if that specific element is empty, using empty? it returns true:

puts my_listing[2].empty?
true

But when I cycle through the entire array, checking to see if i is empty, it doesn't find that particular element.

my_listing.each do |i|
    if i.empty?
        puts i
    end
end

i (in this case 2) is never printed to the screen.

Why is that?

Basically, I am trying to get rid of all the elements in the array that are empty (in this case the element at index 2) but I am not sure how to even get at those elements.

What am I missing?

Thanks.

2 Answers 2

7

You're not seeing anything printed because you forgot to use #inspect You could also just have written:

my_listing.each do |i|
    i.empty? and p i
end

To remove empty elements, you can do the following:

my_array = [[1],[2],[],[4]]

p my_array.reject(&:empty?) # => [[1], [2], [4]]

reject calls #empty? on all the elements and removes the ones which are empty

Sign up to request clarification or add additional context in comments.

Comments

0

Oh please iterate like this

       my_listing.each_with_index do |i,index|
          if i.blank?
             puts index.inspect
          end
       end

It give you index of array which will be empty or nil.

5 Comments

the method .blank? doesn't work, but .empty? does. Thanks.
FYI: this is the error I get when I do .blank? - NoMethodError: undefined method 'blank?' for []:Nokogiri::XML::NodeSet. I am using Nokogiri and am storing a node in an array.
How do I pop an element that is empty? I tried doing i.pop in the each, but that didn't work. Neither did index.pop. Thoughts?
Never mind, I tried reject! like @jessehz suggested and it worked beautifully.
In case you were wondering - .blank? is a Rails extension method which checks for .nil? and .empty? (at least as far as I remember). If you're not in Rails then it would explain why it doesn't work!

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.