2

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?

1

2 Answers 2

7

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"
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for awesomely concise answer. But it seems there is no way to avoid regexes.
@Kulbir: Of course you can avoid regex here, it's just not going to be as concise ;) I think this is because the Python function is a bit special.
Yes, I guess avoiding regex would include looping on the characters and stripping them individually. But this works as well.
Yeah, I think it'd get a bit messy without regex
4

Python's strip is a little unusual. It removes any characters that match any of those in the argument from either end.

I think you need 2 .subs. One to strip from the beginning and one to strip from the end

irb(main):001:0> 'asdf/asdf'.sub(/^[\/]*/, '').sub(/[\/]*$/, '')
=> "asdf/asdf"
irb(main):002:0> 'asdf/asdf'.sub(/^[\/f]*/, '').sub(/[\/f]*$/, '')
=> "asdf/asd"
irb(main):003:0> ' asdf/asdf'.sub(/^[ ]*/, '').sub(/[ ]*$/, '')
=> "asdf/asdf"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.