Ruby string strip defined characters

2020-06-08 14:56发布

问题:

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.

回答1:

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"


回答2:

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

Can also be shortenend to

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


回答3:

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!



回答4:

Try the gsub method:

irb(main):001:0> "[foo ]".gsub(/\As+[/,'')
=> "foo ]"

irb(main):001:0> "foo ]".gsub(/s+]\Z/,'')
=> "foo"

etc.



回答5:

Try the String#delete method: (avaiable in 1.9.3, not sure about other versions)

Ex:

    1.9.3-p484 :003 > "hehhhy".delete("h")
     => "ey"