String.strip / lstrip / rstrip / chomp / chop
Methods that remove leading/trailing whitespace or trailing newlines and characters from a string. Commonly used to normalize user input.
Syntax
# Removes whitespace (spaces, tabs, newlines) from both ends. string.strip # Removes leading whitespace only. string.lstrip # Removes trailing whitespace only. string.rstrip # Removes the trailing newline. string.chomp string.chomp(separator) # Removes the last character. string.chop
Method List
| Method | Description |
|---|---|
| strip | Returns a new string with leading and trailing whitespace (spaces, tabs, newlines) removed. |
| lstrip | Removes leading whitespace only. |
| rstrip | Removes trailing whitespace only. |
| chomp | Removes the trailing newline (\n, \r\n, or \r). You can specify a custom separator as an argument. |
| chop | Unconditionally removes the last character. If the string ends with \r\n, both characters are removed. |
| strip! | Modifies the original string in place (destructive method). |
Sample Code
# Use strip to remove whitespace from both ends.
input = " John Smith "
puts input.strip # John Smith
puts input.lstrip # John Smith (trailing spaces remain)
puts input.rstrip # John Smith (leading spaces remain)
# Use chomp to remove a trailing newline.
line = "data\n"
puts line.chomp # data (no newline)
# Pass an argument to chomp to remove a specific string.
text = "Hello!!!"
puts text.chomp("!") # Hello!! (removes only one occurrence)
# Use chop to remove the last character.
word = "Rubys"
puts word.chop # Ruby
# Remove newlines from each line in an array.
lines = ["apple\n", "banana\n", "cherry\n"]
clean = lines.map(&:chomp)
puts clean.inspect # ["apple", "banana", "cherry"]
# Normalize a form input value.
email = " user@example.com "
normalized = email.strip.downcase
puts normalized # user@example.com
Notes
strip is commonly used to trim whitespace from form input values. All of these methods leave the original string unchanged and return a new string.
Be careful about the difference between chomp and chop. chomp removes the trailing newline only if one is present, whereas chop always removes the last character regardless of what it is. To avoid unexpected character removal, chomp is generally recommended.
To replace characters in a string, use sub / gsub. To split a string, use split.
If you find any errors or copyright issues, please contact us.