13

我想挤红宝石。我在 Ruby on rails 中找到了这种方法,但我只想在 Ruby 中使用它,因为我没有使用 Ruby on rails。

如何在 Ruby 中做到这一点。

" foo   bar    \n   \t   boo".squish # => "foo bar boo"
4

5 回答 5

11

尝试以下操作:

" foo   bar    \n   \t   boo".split.join(" ")
# => "foo bar boo"
于 2013-07-19T08:31:56.237 回答
9

来自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
于 2013-07-19T08:32:43.223 回答
7
>> " foo   bar    \n   \t   boo".strip.gsub(/\s+/, ' ')
=> "foo bar boo"
于 2013-07-19T08:32:57.490 回答
7

我认为没有理由(重新)实现它而不使用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)
于 2013-07-19T08:47:57.563 回答
0

你可以自己实现它:

def squish
  string = strip
  string.gsub!(/\s+/, ' ')
  string
end

这是修改过的 Railssquish!方法。

于 2013-07-19T08:33:21.727 回答