Ruby string strip defined characters

て烟熏妆下的殇ゞ 提交于 2019-12-21 03:24:12

问题


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"


来源:https://stackoverflow.com/questions/3165891/ruby-string-strip-defined-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!