Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
String#tr_s
(::String::selector source, ::string replacement) -> ::String
tr_s(selector, replacements) → new_string
string.c
View on GitHub ↗
static VALUE
rb_str_tr_s(VALUE str, VALUE src, VALUE repl)
{
str = str_duplicate(rb_cString, str);
tr_trans(str, src, repl, 1);
return str;
}
Like String#tr, except:
-
Also squeezes the modified portions of the translated string; see
String#squeeze. -
Returns the translated and squeezed string.
Examples:
Example
'hello'.tr_s('l', 'r') #=> "hero" 'hello'.tr_s('el', '-') #=> "h-o" 'hello'.tr_s('el', 'hx') #=> "hhxo"
Related: see Converting to New String.
Ruby version changes
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-