我想挤红宝石。我在 Ruby on rails 中找到了这种方法,但我只想在 Ruby 中使用它,因为我没有使用 Ruby on rails。
如何在 Ruby 中做到这一点。
" foo bar \n \t boo".squish # => "foo bar boo"
我想挤红宝石。我在 Ruby on rails 中找到了这种方法,但我只想在 Ruby 中使用它,因为我没有使用 Ruby on rails。
如何在 Ruby 中做到这一点。
" foo bar \n \t boo".squish # => "foo bar boo"
尝试以下操作:
" foo bar \n \t boo".split.join(" ")
# => "foo bar boo"
来自Rails 源代码,它增加squish!
了String
:
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 16
def squish!
gsub!(/\A[[:space:]]+/, '')
gsub!(/[[:space:]]+\z/, '')
gsub!(/[[:space:]]+/, ' ')
self
end
>> " foo bar \n \t boo".strip.gsub(/\s+/, ' ')
=> "foo bar boo"
我认为没有理由(重新)实现它而不使用ActiveSupport,您可以在没有整个 Rails 框架的情况下使用它:
require 'active_support/core_ext/string/filters'
" foo bar \n \t boo".squish
# => "foo bar baz"
或者,如果你真的想避免 Rails,你可以使用Ruby Facets:
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)