2013-07-19 99 views
8

我想用紅寶石壓扁。我在Ruby on rails中找到了這個方法,但是我只想在Ruby中使用它,因爲我沒有在rails上使用Ruby。如何在紅寶石中壓扁

在Ruby中如何做到這一點。

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

如果你知道你想要什麼,那麼爲什麼不看它的來源? – sawa

回答

8

嘗試以下操作:

" foo bar \n \t boo".split.join(" ") 
# => "foo bar boo" 
+0

作品完美! –

8

Rails source,增加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 
6
>> " foo bar \n \t boo".strip.gsub(/\s+/, ' ') 
=> "foo bar boo" 
1

你可以自己實現:

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

這是修改Rails'squish!方法。

5

我看不出有任何理由(重新)實現這一點,並沒有使用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" 


更新好吧,也許,perfomarmances可能是一個原因。快速基準:

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)