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.
"[[ ] foo [] boo ][ ]".gsub(/\A[ \[\]]+|[ \[\]]+\Z/,'')
=> "foo [] boo"
Can also be shortenend to
"[[ ] foo [] boo ][ ]".gsub(/\A[][ ]+|[][ ]+\Z/,'')
=> "foo [] boo"
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"
There is no such method in ruby, but you can easily define it like:
class String
alias strip_ws strip
def strip chr=nil
return self.strip_ws if chr.nil?
self.gsub /^[#{Regexp.escape(chr)}]*|[#{Regexp.escape(chr)}]*$/, ''
end
end
Which will satisfy the requested requirements:
> "[ [] foo [] boo [][]] ".strip(" []")
=> "foo [] boo"
While still doing what you'd expect in less extreme circumstances.
> ' _bar_ '.strip.strip('_')
=> "bar"
nJoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With