How to Strip Whitespace in Ruby: Simple Methods Explained
In Ruby, you can remove whitespace from the start and end of a string using the
strip method. To remove whitespace only from the left or right side, use lstrip or rstrip respectively.Syntax
The main methods to remove whitespace in Ruby strings are:
string.strip- removes whitespace from both ends.string.lstrip- removes whitespace from the start (left side).string.rstrip- removes whitespace from the end (right side).
These methods return a new string without changing the original.
ruby
str.strip str.lstrip str.rstrip
Example
This example shows how to use strip, lstrip, and rstrip to remove whitespace from a string.
ruby
str = " Hello, Ruby! " puts "Original: '#{str}'" puts "strip: '#{str.strip}'" puts "lstrip: '#{str.lstrip}'" puts "rstrip: '#{str.rstrip}'"
Output
Original: ' Hello, Ruby! '
strip: 'Hello, Ruby!'
lstrip: 'Hello, Ruby! '
rstrip: ' Hello, Ruby!'
Common Pitfalls
One common mistake is expecting strip to remove whitespace inside the string, but it only removes spaces at the start and end. Also, these methods do not change the original string unless you use their bang versions like strip!.
Using strip! modifies the string in place and returns nil if no changes were made, which can be confusing.
ruby
str = "Hello" # Wrong: expecting strip to remove spaces inside puts str.strip # Output: 'Hello' (no change) # Right: use strip! to modify original str_with_spaces = " Hello " str_with_spaces.strip! puts str_with_spaces # Output: 'Hello'
Output
Hello
Hello
Quick Reference
| Method | Description | Modifies Original? |
|---|---|---|
| strip | Removes whitespace from both ends | No |
| lstrip | Removes whitespace from the start (left) | No |
| rstrip | Removes whitespace from the end (right) | No |
| strip! | Removes whitespace from both ends, modifies original | Yes |
| lstrip! | Removes whitespace from start, modifies original | Yes |
| rstrip! | Removes whitespace from end, modifies original | Yes |
Key Takeaways
Use
strip to remove whitespace from both ends of a string.Use
lstrip or rstrip to remove whitespace only from the left or right side.These methods return a new string; use the bang versions like
strip! to modify the original string.Whitespace inside the string is not removed by these methods.
The bang methods return nil if no changes are made, so check return values carefully.