如何在红宝石中挤压

Vij*_*han 11 ruby

我想要用红宝石压扁.我在Ruby on rails上找到了这个方法,但是我想在Ruby中使用它,因为我没有在rails上使用Ruby.

怎么能在Ruby中做到这一点.

" foo   bar    \n   \t   boo".squish # => "foo bar boo"
Run Code Online (Sandbox Code Playgroud)

Aru*_*hit 10

请尝试以下方法:

" foo   bar    \n   \t   boo".split.join(" ")
# => "foo bar boo"
Run Code Online (Sandbox Code Playgroud)


rid*_*rid 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
Run Code Online (Sandbox Code Playgroud)


fal*_*tru 6

>> " foo   bar    \n   \t   boo".strip.gsub(/\s+/, ' ')
=> "foo bar boo"
Run Code Online (Sandbox Code Playgroud)


tor*_*o2k 5

我认为没有理由(重新)实现它而不使用ActiveSupport,你可以在没有整个Rails框架的情况下使用它:

require 'active_support/core_ext/string/filters'
" foo   bar    \n   \t   boo".squish
# => "foo bar baz"
Run Code Online (Sandbox Code Playgroud)

或者,如果你真的想避免使用Rails,你可以使用Ruby Facets:

require 'facets/string/squish'
" foo   bar    \n   \t   boo".squish
# => "foo bar baz"
Run Code Online (Sandbox Code Playgroud)


更新嗯,也许,性能可能是一个原因.快速基准:

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)
Run Code Online (Sandbox Code Playgroud)