红宝石 |字符串 gsub!方法
gsub!是 Ruby 中的 String 类方法,用于返回给定字符串的副本,其中所有出现的模式都替换为第二个参数。如果没有执行替换,那么它将返回 nil。如果没有给出块并且没有给出替换,则返回一个枚举器。
Syntax: str.gsub!(pattern, replacement)
Parameters: Here, str is the given string. pattern may be specified regex or character set to be removed. replacement is the set of characters which is to be put.
Returns: A copy of the string with all occurrences of pattern substituted for the second argument or nil if no substitutions were performed.
示例 1:
# Ruby program to demonstrate
# the gsub! method
# Taking a string and
# using the method
puts "Sample".gsub!(/[bcd]/, '*')
puts "Program".gsub!(/([gmra])/, '<\1>')
输出:
Po
示例 2:
# Ruby program to demonstrate
# the gsub! method
# Taking a string and
# using the method
puts "Ruby".gsub!(/[tyru]/, '<\1>')
puts "String".gsub!(/([ab])/, '*')
输出:
Rb