📜  红宝石 |字符串 gsub 方法(1)

📅  最后修改于: 2023-12-03 15:41:12.304000             🧑  作者: Mango

红宝石 | 字符串 gsub 方法

Ruby中,gsub是一个用于替换字符串中所有匹配内容的方法。

用法
string.gsub(pattern, replacement)

其中,string表示源字符串,pattern表示需要匹配的模式(可以是字符串或正则表达式),replacement则是进行替换的字符串。

示例
# 示例一
str = "hello world"
new_str = str.gsub("o", "0")
puts new_str  # 输出:hell0 w0rld

# 示例二
str = "hello world"
new_str = str.gsub(/[aeiou]/, "")
puts new_str  # 输出:hll wrld
灵活运用

使用 gsub 方法的一个常见用法就是过滤掉字符串中的特定字符或字符串。

# 过滤掉字符 a 和字符 e
str = "beyond"
new_str = str.gsub(/[ae]/, "")
puts new_str  # 输出:byond

在上述示例中,使用正则表达式对模式进行匹配,替换掉了字符 a 和字符 e。

也可以使用 gsub 方法将字符串中的某个单词替换为另一个单词。比如将字符串 "I love Ruby" 中的 Ruby 替换为 Python。

str = "I love Ruby"
new_str = str.gsub("Ruby", "Python")
puts new_str  # 输出:I love Python
总结

通过本文的介绍,我们可以看到 gsub 方法的强大之处,它可以帮助我们方便地进行字符或字符串的替换。而要注意的是,它会替换掉所有匹配的内容,因此使用时要谨慎。