Ruby string strip defined characters
In Python, we can use the .strip()
method of a string to remove lea开发者_如何转开发ding 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.
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"
"[[ ] 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:
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!
Try the gsub method:
irb(main):001:0> "[foo ]".gsub(/\As+[/,'')
=> "foo ]"
irb(main):001:0> "foo ]".gsub(/s+]\Z/,'')
=> "foo"
etc.
You can use: str.chomp('.') that works for trailing characters and you can reverse the string for leading characters: str.reverse.chomp('.').reverse
To do both at once you can: str.chomp('.').reverse.chomp('.').reverse
Note: chomp removes only one occurrence by default
Ruby now includes full support for stripping with
lstrip: Strips only leading part of string rstrip: Strips only ending part of string strip: Strips both leading and ending of string
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"
精彩评论