Search code examples
arraysrubytrim

How do I "trim" my array of strings?


With Ruby, I'm curious about how to remove the leading and ending elements of an array of strings if those elements are blank (either nil or the empty string). If I have an array of

["", "a", "", "b", nil, ""]

I would want the result to be

["a", "", "b"]

I found a partial way to remove the right non-present elements of an array using

arr.pop until arr.last || arr.empty?

But that seems to only work with trimming the nil elements of the end of my array. It doesn't address empty strings or removing the blank elements from the front of an array.


Solution

  • array.
     drop_while { |element| element.nil? || element.empty? }.
     reverse.
     drop_while { |element| element.nil? || element.empty? }.
     reverse
    

    If you want to remove the repetition:

    blank = ->(element) { element.nil? || element.empty? }
    
    array.drop_while(&blank).reverse.drop_while(&blank).reverse
    

    If you are using active support, you can do it directly:

    array.drop_while(&:blank?).reverse.drop_while(&:blank?).reverse