Ruby 字符串条带定义的字符 [英] Ruby string strip defined characters
本文介绍了Ruby 字符串条带定义的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 中,我们可以使用 .strip()
删除所选字符的前导或尾随出现的字符串方法:
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'
我们如何在 Ruby 中做到这一点?Ruby 的 strip
方法不接受任何参数,只去除空格.
How do we do this in Ruby? Ruby's strip
method takes no arguments and strips only whitespace.
推荐答案
ruby 中没有这样的方法,但是你可以很容易地定义它:
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"
这篇关于Ruby 字符串条带定义的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文