Search code examples
rubystringwhitespacestrip

Ruby: How to strip a string and get the removed whitespaces?


Given a string, I would like to strip it, but I want to have the pre and post removed whitespaces. For example:

my_strip("   hello world ")   # => ["   ", "hello world", " "]
my_strip("hello world\t ")    # => ["", "hello world", "\t "]
my_strip("hello world")       # => ["", "hello world", ""]

How would you implement my_strip ?


Solution

  • Solution

    def my_strip(str)
      str.match /\A(\s*)(.*?)(\s*)\z/m
      return $1, $2, $3
    end
    

    Test Suite (RSpec)

    describe 'my_strip' do
      specify { my_strip("   hello world ").should      == ["   ", "hello world", " "]     }
      specify { my_strip("hello world\t ").should       == ["", "hello world", "\t "]      }
      specify { my_strip("hello world").should          == ["", "hello world", ""]         }
      specify { my_strip(" hello\n world\n \n").should  == [" ", "hello\n world", "\n \n"] }
      specify { my_strip(" ... ").should                == [" ", "...", " "]               }
      specify { my_strip(" ").should                    == [" ", "", ""]                   }
    end