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

时间:2016-11-11 11:16:21

标签: ruby-on-rails ruby

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

之间有区别吗?
string.gsub(/\s+/, '')

string.strip

如果是这样,它是什么?

1 个答案:

答案 0 :(得分:1)

strip仅删除前导空格和尾随空格,使用gsub按照您在问题中勾勒出来的方式删除字符串中的所有空格。

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"