How do I remove repeated spaces in a string?

String#squeeze has an optional parameter to specify characters to squeeze.

irb> "asd  asd asd   asd".squeeze(" ")
=> "asd asd asd asd"

Warning: calling it without a parameter will ‘squezze’ ALL repeated characters, not only spaces:

irb> 'aaa     bbbb     cccc 0000123'.squeeze
=> "a b c 0123"

Leave a Comment