Dimitri de Ruiter Dimitri de Ruiter - 11 months ago 61
Ruby Question

Ruby: stringA.gsub(/\s+/, '') versus stringA.strip

Say

string = "Johnny be good! And smile :-) "


Is there a difference between

string.gsub(/\s+/, '')


and

string.strip


?

If so, what is it?

Answer Source

strip only removes leading and trailing whitespace, using gsub in the way that you outline in your question will remove all whitespace from the string.

irb(main):004:0* " hello ".strip
=> "hello"
irb(main):005:0> " h e l l o ".strip
=> "h e l l o"
irb(main):006:0> " hello ".gsub(/\s+/, '')
=> "hello"
irb(main):007:0> " h e l l o ".gsub(/\s+/, '')
=> "hello"