instance method
String#chomp
(?::string? separator) -> ::String
chomp(line_sep = $/) → new_string
string.c
View on GitHub ↗
static VALUE
rb_str_chomp(int argc, VALUE *argv, VALUE str)
{
VALUE rs = chomp_rs(argc, argv);
if (NIL_P(rs)) return str_duplicate(rb_cString, str);
return rb_str_subseq(str, 0, chompped_length(str, rs));
}
Returns a new string copied from self, with trailing characters possibly removed:
When line_sep is "\n", removes the last one or two characters if they are "\r", "\n", or "\r\n" (but not "\n\r"):
Example
$/ # => "\n" "abc\r".chomp # => "abc" "abc\n".chomp # => "abc" "abc\r\n".chomp # => "abc" "abc\n\r".chomp # => "abc\n" "тест\r\n".chomp # => "тест" "こんにちは\r\n".chomp # => "こんにちは"
When line_sep is '' (an empty string), removes multiple trailing occurrences of "\n" or "\r\n" (but not "\r" or "\n\r"):
Example
"abc\n\n\n".chomp('') # => "abc" "abc\r\n\r\n\r\n".chomp('') # => "abc" "abc\n\n\r\n\r\n\n\n".chomp('') # => "abc" "abc\n\r\n\r\n\r".chomp('') # => "abc\n\r\n\r\n\r" "abc\r\r\r".chomp('') # => "abc\r\r\r"
When line_sep is neither "\n" nor '', removes a single trailing line separator if there is one:
Example
'abcd'.chomp('cd') # => "ab" 'abcdcd'.chomp('cd') # => "abcd" 'abcd'.chomp('xx') # => "abcd"
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]
-