marcamillion marcamillion - 5 months ago 36
Ruby Question

Checking for empty elements within my array - Ruby

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.

Answer

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.