Chomp example. This removes the newline characters from the end of a string. So it will remove "\n" or "\r\n" if those characters are at the end. A substring is removed if it is present.
# Chomp removes ending whitespace and returns a copy.
value = "egypt\r\n"
value2 = value.chomp
# Chomp! modifies the string in-place.
value3 = "england\r\n"
# An argument specifies apart to be removed.
value4 = "european"
Strip. This method is sometimes called trim(): it removes all leading and trailing whitespace. Spaces, newlines, and other whitespace like tab characters are eliminated.
Detail We invoke strip with an exclamation mark to modify the string in-place. The leading space and trailing newline are removed.
Detail We call chomp to see how it differs from strip. With chomp, the leading space is left alone.
# Part A: strip removes leading and trailing whitespace.
value1 = " bird\n"
puts "[" + value1 + "]"# Part B: chomp does not remove spaces, only newlines.
value2 = " bird\n"
puts "[" + value2 + "]"[bird]
Chop. Here we use the chop() method. This method is similar to chomp, but less safe. It removes the final character from the input. This can lead to corrupt data.
Detail This code shows that the last character in a string is always removed with chop—even if it is not whitespace.
Detail Chomp() is safer than chop, as it will not remove an ending char unless it is a newline character.
# Part A: chop removes the last character.
value1 = "cat"
puts "[" + value1 + "]"# Part B: chomp only removes a newline at the end.
value2 = "cat"
puts "[" + value2 + "]"[ca]
A review. When processing text in Ruby programs, we usually need to remove certain leading trailing characters. Strip() is a versatile method, but chomp() and chop can also be useful.