Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete empty strings in array

I want to get delete_if to delete empty strings from an array. With the solution below, the array still contains many empty strings.

products = my_text.split(/\t+/)
products.delete_if {|element| element == " " || "" || element.nil?}

Is there anything missing?

like image 534
Adam Bronfin Avatar asked Aug 24 '26 09:08

Adam Bronfin


1 Answers

The problem with your code is explained by Ed S.
Otherwise, you can do

products.reject! { |s| s.nil? || s.strip.empty? }

Why do you need to test nil? first? Let's check few lines.

nil.strip
# NoMethodError: undefined method `strip' for nil:NilClass
"   ".strip
# => ""

Now, with a different order, what the code does if the object is a string, and then if it is nil.

"  ".strip || "  ".nil?
# => ""
nil.strip || nil.nil?
# NoMethodError: undefined method `strip' for nil:NilClass
# Oh you don't want that to happen, do you?

This means you don't want to call strip.empty? when your object is nil.
And as you know, when you have a || b, if a is truthy (i.e. not nil nor false), b will never be called.
You test first if the string is nil ; if it is, you don't need to check the right part (so you won't get a undefined method error) and the object will be removed from your products list.

like image 61
oldergod Avatar answered Aug 27 '26 00:08

oldergod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!