Skip to content
instance method

String#chomp

(?::string? separator) -> ::String
chomp(line_sep = $/) → new_string

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

  1. 3.0
See also #chomp! #chars #center #chop also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0