Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string strip defined characters

Tags:

string

ruby

strip

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.

like image 648
mykhal Avatar asked Jul 02 '10 13:07

mykhal


3 Answers

"[[ ] foo [] boo ][ ]".gsub(/\A[ \[\]]+|[ \[\]]+\Z/,'') 
=> "foo [] boo"

Can also be shortenend to

"[[ ] foo [] boo ][ ]".gsub(/\A[][ ]+|[][ ]+\Z/,'') 
=> "foo [] boo"
like image 42
Tim Pietzcker Avatar answered Sep 30 '22 13:09

Tim Pietzcker


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"
like image 167
sepp2k Avatar answered Sep 30 '22 14:09

sepp2k


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!

like image 30
nickl- Avatar answered Sep 30 '22 12:09

nickl-