Ruby string strip defined characters

mykhal picture mykhal · Jul 2, 2010 · Viewed 10.6k times · Source

In Python, we can use the .strip() method of a string to remove leading or trailing occurrences of chosen characters:

>>> print " (Removes (only) leading & trailing brackets & ws ) ".strip(" ()")
'Removes (only) leading & trailing brackets & ws'

How do we do this in Ruby? Ruby's strip method takes no arguments and strips only whitespace.

Answer

sepp2k picture sepp2k · Jul 2, 2010

There is no such method in ruby, but you can easily define it like:

def my_strip(string, chars)
  chars = Regexp.escape(chars)
  string.gsub(/\A[#{chars}]+|[#{chars}]+\z/, "")
end

my_strip " [la[]la] ", " []"
#=> "la[]la"