How To Trim In Ruby

When working with text data in Ruby, you might often come across scenarios where you need to remove leading and trailing whitespace characters from a string. This is called “trimming” a string. In this blog post, we will explore different ways to trim strings in Ruby.

Method 1: Using strip and strip! methods

The most straightforward and commonly used methods to trim a string in Ruby are strip and strip!. Both methods remove leading and trailing white spaces from a string, but they work in slightly different ways.

Using strip

The strip method returns a new string with leading and trailing white spaces removed, leaving the original string unchanged.

    text = "   Hello, World!   "
    trimmed_text = text.strip
    puts trimmed_text
    #=> "Hello, World!"
    puts text
    #=> "   Hello, World!   "
    

Using strip!

The strip! method, on the other hand, removes leading and trailing white spaces from the original string and returns nil if no changes were made. Note that this method modifies the original string.

    text = "   Hello, World!   "
    text.strip!
    puts text
    #=> "Hello, World!"
    

Method 2: Using Regular Expressions

You can also use regular expressions to trim a string in Ruby. This is particularly useful when you need more control over the characters being removed from the string.

Using sub and gsub methods

By using the sub and gsub methods with a regular expression, you can remove leading and trailing white spaces from a string. The sub method only replaces the first occurrence, whereas the gsub method replaces all occurrences.

    text = "   Hello, World!   "
    trimmed_text = text.gsub(/^\s+|\s+$/, '')
    puts trimmed_text
    #=> "Hello, World!"
    

Conclusion

In this blog post, we’ve discussed different ways of trimming strings in Ruby. The most common methods are using strip and strip! methods, but you can also use regular expressions if you need more control over the characters being removed. Always choose the method that best fits your requirements and helps you write clean and efficient code.