require 'facets/string/squish'
" foo bar \n \t boo".squish
# => "foo bar baz"
更新嗯,也许,性能可能是一个原因。一个快速的基准:
require 'benchmark'
require 'facets/string/squish'
def squish_falsetru(s)
s.strip.gsub(/s+/, ' ')
end
def squish_priti(s)
s.split.join(' ')
end
# ActiveSupport's implementation is not included to avoid
# names clashes with facets' implementation.
# It is also embarrassing slow!
N = 500_000
S = " foo bar \n \t boo"
Benchmark.bm(10) do |x|
x.report('falsetru') { N.times { squish_falsetru(S) } }
x.report('priti') { N.times { squish_priti(S) } }
x.report('facets') { N.times { S.squish } }
end
user system total real
falsetru 1.050000 0.000000 1.050000 ( 1.047549)
priti 0.870000 0.000000 0.870000 ( 0.879500)
facets 2.740000 0.000000 2.740000 ( 2.746178)
class String
def squish
strip.gsub(/\s+/, ' ')
end
end
示范:
$ irb
irb(main):001:1* class String
irb(main):002:2* def squish
irb(main):003:2* strip.gsub(/\s+/, ' ')
irb(main):004:1* end
irb(main):005:0> end
=> :squish
irb(main):006:0> " Help, I am trapped in a computer ".squish
=> "Help, I am trapped in a computer"
6条答案
按热度按时间uidvcgyl1#
请尝试以下操作:
brjng4g32#
在Rails源代码中,将
squish!
添加到String
:u1ehiz5o3#
我认为没有理由(重新)实现它而不使用ActiveSupport,您可以在没有整个Rails框架的情况下使用它:
或者,如果您真的不想使用Rails,可以使用Ruby Facets:
更新嗯,也许,性能可能是一个原因。一个快速的基准:
ev7lccsx4#
xmjla07d5#
您可以自行实施:
它修改了Rails的
squish!
方法。wlzqhblo6#
这将向Ruby
String
类添加一个行为类似于Rail的squish
方法的方法:示范: