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
