liveBook · Manning

Chomp

As explained in The Well-Grounded Rubyist, Fourth Edition

chomp is a Ruby String method that removes a specified record separator from the end of a string when present, defaulting to a newline.

Ruby's chomp removes a target substring from the end of a string only when that substring is present. With no argument, the target is the newline character, making chomp especially useful for lines returned by gets. section 8.1.5

Removing a newline or chosen suffix

"David A. Black\n".chomp # => "David A. Black" "David A. Black".chomp('ck') # => "David A. Bla" Unlike chomp, chop removes one character unconditionally, even when it is not a newline. Both methods also have bang variants that modify the receiver in place. section 8.1.5

>> "David A. Black".chop
=> "David A. Blac"
>> "David A. Black\n".chomp
=> "David A. Black"
>> "David A. Black".chomp('ck')
=> "David A. Bla"

Compare unconditional character removal with newline removal and custom suffix removal through short IRB examples. section 8.1.5

A common file-processing pattern reads each line with gets, chompes its trailing newline, and then splits the cleaned record for further processing. File.open's block scopes the file operation, but the loop still performs the reading explicitly. section 12.2.7

Listing 12.2 Using the block-based version of File.open
records.txt:
Pablo Casals|Catalan|cello|1876-1973
Jascha Heifetz|Russian-American|violin|1901-1988
Emanuel Feuermann|Austrian-American|cello|1902-1942
read_records.rb:
File.open("records.txt") do |f|
  while record = f.gets        
    name, nationality, instrument, dates = record.chomp.split('|')
    puts "#{name} (#{dates}), who was #{nationality},
➥played {instrument}."
  end
end

Follow a complete records.txt example that chompes each input line before splitting pipe-separated fields and formatting output. section 12.2.7

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines chomp through contrasts, custom suffixes, bang variants, and a worked file-processing pattern.
Examples
Uses IRB string comparisons and a pipe-delimited musician-record file parsed line by line.
What you can do after
Apply it via Ruby's String#chomp to clean input lines or remove a specified trailing substring.
How it connects
Links chomp to String transformation, chop, gets, File.open, while loops, split, and bang methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.