Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 780
Kulbir Saini Avatar asked Mar 01 '26 13:03

Kulbir Saini


1 Answers

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"
like image 119
Niklas B. Avatar answered Mar 04 '26 01:03

Niklas B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!