Voglio squish in rubino. Ho trovato questo metodo in Ruby su rotaie ma voglio usarlo in Ruby solo perché non ho usato Ruby su rotaie.Come squish in rubino
Come farlo in Ruby.
" foo bar \n \t boo".squish # => "foo bar boo"
Voglio squish in rubino. Ho trovato questo metodo in Ruby su rotaie ma voglio usarlo in Ruby solo perché non ho usato Ruby su rotaie.Come squish in rubino
Come farlo in Ruby.
" foo bar \n \t boo".squish # => "foo bar boo"
Provare quanto segue:
" foo bar \n \t boo".split.join(" ")
# => "foo bar boo"
funziona perfettamente !! –
Dal Rails source, che aggiunge 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"
È possibile implementare da soli:
def squish
string = strip
string.gsub!(/\s+/, ' ')
string
end
È stato modificato il metodo squish!
di Rails.
vedo alcun motivo per (ri) mettere in atto questo e non utilizzare ActiveSupport, si può utilizzare senza l'intero quadro Rails:
require 'active_support/core_ext/string/filters'
" foo bar \n \t boo".squish
# => "foo bar baz"
Oppure, se si vuole davvero evitare Rails, è possibile utilizzare Ruby Facets :
require 'facets/string/squish'
" foo bar \n \t boo".squish
# => "foo bar baz"
aggiornamento Be ', forse, perfomarmances potrebbe essere un motivo. Un rapido punto di riferimento:
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)
Se sai esattamente quello che vuoi, allora perché non guardare la sua fonte? – sawa