Skip to Content

`tr` vs `gsub`

Posted on
  • Use tr when we want to replace single characters

tr will 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.

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

  'abcde'.tr('bcd', '123')
  #=> "a123e"
  • Use gsub when we want to replace longer substrings or when we want to use regular expression.
  'abcde'.gsub(/bda/, '123')
  #=> "abcde"

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

References:

comments powered by Disqus