Ruby 字符串的 gsub 和 sub 方法有什么区别 [英] What is the difference between gsub and sub methods for Ruby Strings

查看:74
本文介绍了Ruby 字符串的 gsub 和 sub 方法有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我一直在阅读 String 的文档,我看到了 :sub 方法,这是我以前从未注意到的.我一直在使用 :gsub 并且它们似乎基本相同.任何人都可以向我解释其中的区别吗?谢谢!

I have been perusing the documentation for String today, and I saw the :sub method, which I'd never noticed before. I've been using :gsub and it appears that they are essentially the same. Can anyone explain the difference to me? Thanks!

推荐答案

g 代表 global,如替换 global (all):

The g stands for global, as in replace globally (all):

在 irb 中:

>> "hello".sub('l', '*')
=> "he*lo"
>> "hello".gsub('l', '*')
=> "he**o"

这篇关于Ruby 字符串的 gsub 和 sub 方法有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆