VOOZH about

URL: https://apidock.com/ruby/String/tr

⇱ String#tr - APIdock


method

tr

ruby latest stable - Class: String
tr(p1, p2)
public

Returns a copy of with the characters in replaced by the corresponding characters in . If is shorter than it is padded with its last character in order to maintain the correspondence.

"hello".tr('el', 'ip') #=> "hippo"
"hello".tr('aeiou', '*') #=> "h*ll*"
"hello".tr('aeiou', 'AA*') #=> "hAll*"

Both strings may use the c1-c2 notation to denote ranges of characters, and may start with a ^, which denotes all characters except those listed.

"hello".tr('a-y', 'b-z') #=> "ifmmp"
"hello".tr('^aeiou', '*') #=> "*e**o"

The backslash character \ can be used to escape ^ or - and is otherwise ignored unless it appears at the end of a range or the end of the or

"hello^world".tr("\\^aeiou", "*") #=> "h*ll**w*rld"
"hello-world".tr("a\\-eo", "*") #=> "h*ll**w*rld"

"hello\r\nworld".tr("\r", "") #=> "hello\nworld"
"hello\r\nworld".tr("\\r", "") #=> "hello\r\nwold"
"hello\r\nworld".tr("\\\r", "") #=> "hello\nworld"

"X['\\b']".tr("X\\", "") #=> "['b']"
"X['\\b']".tr("X-\\]", "") #=> "'b'"
static VALUE
rb_str_tr(VALUE str, VALUE src, VALUE repl)
{
 str = rb_str_dup(str);
 tr_trans(str, src, repl, 0);
 return str;
}

Related methods