Search code examples
pythonrubystringstrip

How to achieve Python like string strip in Ruby?


In Python, I can strip white-spaces, new lines or random characters from strings like

>>> '/asdf/asdf'.strip('/')
'asdf/asdf' # Removes / from start
>>> '/asdf/asdf'.strip('/f')
'asdf/asd' # Removes / from start and f from end
>>> ' /asdf/asdf '.strip()
'/asdf/asdf' # Removes white space from start and end
>>> '/asdf/asdf'.strip('/as')
'df/asdf' # Removes /as from start
>>> '/asdf/asdf'.strip('/af')
'sdf/asd' # Removes /a from start and f from end

But Ruby's String#strip method accepts no arguments. I can always fall back to using regular expressions but is there a method/way to strip random characters from strings (rear and front) in Ruby without using regular expressions?


Solution

  • You can use regular expressions:

    "atestabctestcb".gsub(/(^[abc]*)|([abc]*$)/, '')
    # => "testabctest"
    

    Of course you can make this a method as well:

    def strip_arbitrary(s, chars)
        r = chars.chars.map { |c| Regexp.quote(c) }.join
        s.gsub(/(^[#{r}]*)|([#{r}]*$)/, '')
    end
    
    strip_arbitrary("foobar", "fra") # => "oob"