Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between tr and gsub?

Tags:

ruby

People also ask

What does GSUB mean?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.

What is the difference between gsub () and sub ()?

The difference is that sub only replaces the first occurrence of the pattern specified, whereas gsub does it for all occurrences (that is, it replaces globally).

What does GSUB return?

gsub (s, pattern, repl [, n]) Returns a copy of s in which all (or the first n , if given) occurrences of the pattern have been replaced by a replacement string specified by repl , which can be a string, a table, or a function.

What is TR in Ruby?

The tr() is an inbuilt method in Ruby returns the trace i.e., sum of diagonal elements of the matrix. Syntax: mat1.tr() Parameters: The function needs the matrix whose trace is to be returned.


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"

  • tr can only replace a single character with a single fixed character (although you can put multiple matches of this sort in a single tr call) but is fast.
  • gsub can match complicated patterns using regex, and replace with a complicated computation result, but is slower than tr.

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