What is the difference between tr and gsub?

后端 未结 3 1850
没有蜡笔的小新
没有蜡笔的小新 2020-12-12 18:24

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

3条回答
  •  再見小時候
    2020-12-12 19:21

    Use tr when you want to replace (translate) single characters.

    tr matches on single characters (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:

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

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

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

提交回复
热议问题