String chomp, strip, chop Examples
This page was last reviewed on Feb 1, 2024.
Dot Net Perls
Chomp, strip, chop. Sometimes we need to trim characters from the start or end of strings. With chomp, strip and chop, we can remove leading and trailing chars.
With chomp, we remove trailing newlines only (unless a custom argument is provided). Strip removes leading and trailing whitespace. Chop removes the last char.
String ljust
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 puts value2 # Chomp! modifies the string in-place. value3 = "england\r\n" value3.chomp! puts value3 # An argument specifies apart to be removed. value4 = "european" value4.chomp! "an" puts value4
egypt england europe
Strip. This method is sometimes called trim(): it removes all leading and trailing whitespace. Spaces, newlines, and other whitespace like tab characters are eliminated.
Part 1 We invoke strip with an exclamation mark to modify the string in-place. The leading space and trailing newline are removed.
Part 2 We call chomp to see how it differs from strip. With chomp, the leading space is left alone.
# Part 1: strip removes leading and trailing whitespace. value1 = " bird\n" value1.strip! puts "[" + value1 + "]" # Part 2: chomp does not remove spaces, only newlines. value2 = " bird\n" value2.chomp! puts "[" + value2 + "]"
[bird] [ 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.
Part 1 This code shows that the last character in a string is always removed with chop—even if it is not whitespace.
Part 2 Chomp() is safer than chop, as it will not remove an ending char unless it is a newline character.
# Part 1: chop removes the last character. value1 = "cat" value1.chop! puts "[" + value1 + "]" # Part 2: chomp only removes a newline at the end. value2 = "cat" value2.chomp! puts "[" + value2 + "]"
[ca] [cat]
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 1, 2024 (edit).
© 2007-2024 Sam Allen.