Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

String#chop

() -> ::String
chop → new_string

Returns a new string copied from self, with trailing characters possibly removed.

Removes "\r\n" if those are the last two characters.

Example
"abc\r\n".chop      # => "abc"
"こんにちは\r\n".chop # => "こんにちは"

Otherwise removes the last character if it exists.

Example
'abcd'.chop     # => "abc"
'こんにちは'.chop # => "こんにち"
''.chop         # => ""

If you only need to remove the newline separator at the end of the string, String#chomp is a better alternative.

Related: see Converting to New String.

Ruby version changes

  1. 3.0
See also #chop! #chomp! #chomp #chr also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0