Check Array Contains only Blank Strings in Ruby

This is a nice trick that I recently learned. So, this is a part of an app integration with Google Sheet. The array is an interpretation of a row. The app should check if all the values inside the row is valid, but should skip if the row is empty. Now sometimes people left some space unintentionally inside some cells. These cells technically are not empty, but I wish the app is smart enough to detect this and mark the row as empty.

For example:

my_array = ["    ", "  ", "", "       "]

I have to detect my_array as an array of blank string

So here’s the check that I use: { |e| e.gsub(/[[:space:]]/, "") }.uniq == [""]

Here’s another check that use Rails, based on some input that I got (thanks guys)

my_array is the array that you want to check. gsub will deletes all spaces inside string element of the array. then uniq equality will check if there is any non empty string left.

Ok, hopefully this trick can be useful for other people. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *