DEV Community

Ahmad khattab
Ahmad khattab

Posted on

3 2

Discoveries in Ruby(and Rails): String#squish

How many times have you had a string that has some extra whitespace in the start/mid/end of a string. To remove them you would have to use strip that would successfully remove the whitespace at the end of a string. Let's see

"   Hello,    World     ".strip
 => "Hello,    World" 

Enter fullscreen mode Exit fullscreen mode

It has successfully removed the whitespaces at the start and end. But what about the middle ones?. Usually you would have to write a regex for that

"   Hello,    World     ".strip.gsub(/[[:space:]]+/, " ")
 => "Hello, World" 
Enter fullscreen mode Exit fullscreen mode

When using Rails. This method is available as String#squish
which does the same thing!

"Hello,      World    ".squish
 => "Hello, World" 
Enter fullscreen mode Exit fullscreen mode

Resources

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay