What is the difference between tr and gsub?

后端 未结 3 1865
没有蜡笔的小新
没有蜡笔的小新 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:06

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

    gsub returns a copy of str with 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. \d will match a backlash followed by d, instead of a digit. http://apidock.com/ruby/String/gsub

提交回复
热议问题