Dimitri de Ruiter Dimitri de Ruiter - 7 months ago 49
Ruby Question

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


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

Is there a difference between

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




If so, what is it?


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"