Ruby字符串定义字符

前端之家收集整理的这篇文章主要介绍了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"
原文链接:https://www.f2er.com/ruby/273407.html

猜你在找的Ruby相关文章