ruby tr 和 gsub 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26749065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:37:36  来源:igfitidea点击:

What is the difference between tr and gsub?

ruby

提问by spickermann

I was reading the Ruby documentation and got confused with the difference between gsuband tr. What is the difference between the two?

我读了Ruby文档和与得到之间的区别感到困惑gsubtr。两者有什么区别?

回答by spickermann

Use trwhen you want to replace (translate) single characters.

使用tr时要替换(翻译)单个字符。

trmatches on singlecharacters (not via a regular expression), therefore the characters don't need to occur in the same order in the first string argument. When a character is found, it is replaced with the character that is found at the same index in the second string argument:

tr匹配单个字符(不是通过正则表达式),因此字符不需要在第一个字符串参数中以相同的顺序出现。当找到一个字符时,它被替换为在第二个字符串参数中的相同索引处找到的字符:

'abcde'.tr('bda', '123')
#=> "31c2e"

'abcde'.tr('bcd', '123')
#=> "a123e"

Use gsubwhen you need to use a regular expression or when you want to replace longer substrings:

使用gsub时,你需要使用正则表达式或当你想更换更长的字符串:

'abcde'.gsub(/bda/, '123')
#=> "abcde"

'abcde'.gsub(/b.d/, '123')
#=> "a123e"

回答by sawa

  • trcan only replace a single character with a single fixed character (although you can put multiple matches of this sort in a single trcall) but is fast.
  • gsubcan match complicated patterns using regex, and replace with a complicated computation result, but is slower than tr.
  • tr只能用单个固定字符替换单个字符(尽管您可以在一次tr调用中放置多个此类匹配项)但速度很快。
  • gsub可以使用正则表达式匹配复杂的模式,并替换为复杂的计算结果,但比tr.

回答by Joel

trreturns a copy of strwith the characters in from_strreplaced by the corresponding characters in to_str. If to_stris shorter than from_str, it is padded with its last character in order to maintain the correspondence. http://apidock.com/ruby/String/tr

tr返回 的副本 中str的字符from_str替换为 中的相应字符to_str。如果to_str小于from_str,则用其最后一个字符填充以保持对应关系。 http://apidock.com/ruby/String/tr

gsubreturns a copy of strwith the all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. \dwill match a backlash followed by d, instead of a digit. http://apidock.com/ruby/String/gsub

gsub返回一个副本,str其中所有出现的模式替换了第二个参数。该模式通常是一个正则表达式;如果作为字符串给出,它包含的任何正则表达式元字符都将按字面解释,例如\d将匹配后跟d, 而不是数字的反斜杠。 http://apidock.com/ruby/String/gsub