我只是想知道是否有任何方法从另一个字符串删除字符串? 就像这样:
class String
def remove(s)
self[s.length, self.length - s.length]
end
end
我只是想知道是否有任何方法从另一个字符串删除字符串? 就像这样:
class String
def remove(s)
self[s.length, self.length - s.length]
end
end
当前回答
Ruby是2。5 +。
如果你的子字符串位于字符串的开头或结尾,那么Ruby 2.5引入了这样的方法:
Delete_prefix用于从字符串的开头删除子字符串 Delete_suffix用于从字符串末尾删除子字符串
其他回答
你可以使用切片方法:
a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"
有一个非!的版本。更多信息可以在其他版本的文档中看到: http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21
如果它是字符串的结尾,你也可以使用chomp:
"hello".chomp("llo") #=> "he"
如果你正在使用rails或较少的activesupport,你得到String#remove和String#remove!方法
def remove!(*patterns)
patterns.each do |pattern|
gsub! pattern, ""
end
self
end
来源:http://api.rubyonrails.org/classes/String.html method-i-remove
Ruby是2。5 +。
如果你的子字符串位于字符串的开头或结尾,那么Ruby 2.5引入了这样的方法:
Delete_prefix用于从字符串的开头删除子字符串 Delete_suffix用于从字符串末尾删除子字符串
str.gsub("subString", "")呢? 看看Ruby Doc