Ruby字符串定义了字符

在Python中,我们可以使用字符串的.strip()方法来删除所选字符的前导或尾随出现:

 >>> print " (Removes (only) leading & trailing brackets & ws ) ".strip(" ()") 'Removes (only) leading & trailing brackets & ws' 

我们如何在Ruby中做到这一点? Ruby的strip方法不带参数,只剥离空格。

在ruby中没有这样的方法,但你可以很容易地定义它:

 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" 

也可以短路到

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

在ruby中没有这样的方法,但你可以很容易地定义它:

 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 

这将满足要求的要求:

 > "[ [] foo [] boo [][]] ".strip(" []") => "foo [] boo" 

虽然仍然在不太极端的情况下做你期望的事情。

 > ' _bar_ '.strip.strip('_') => "bar" 

的nJoy!

尝试使用String#delete方法:(在1.9.3中可用,不确定其他版本)

例如:

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

尝试gsub方法:

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

等等