End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
String#chomp
str.chomp(separator=$/) → new_str
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 with the given record separator removed from the end of str (if present). If $/ has not been changed from the default Ruby record separator, then chomp also removes carriage return characters (that is, it will remove \n, \r, and \r\n). If $/ is an empty string, it will remove all trailing newlines from the string.
Example
"hello".chomp #=> "hello" "hello\n".chomp #=> "hello" "hello\r\n".chomp #=> "hello" "hello\n\r".chomp #=> "hello\n" "hello\r".chomp #=> "hello" "hello \n there".chomp #=> "hello \n there" "hello".chomp("llo") #=> "he" "hello\r\n\r\n".chomp('') #=> "hello" "hello\r\n\r\r\n".chomp('') #=> "hello\r\n\r"
Ruby version changes
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-