Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to squish in ruby

Tags:

ruby

I want to squish in ruby. I have found this method in Ruby on rails but I want to use it in Ruby only because I have not use Ruby on rails.

How can do that in Ruby.

" foo   bar    \n   \t   boo".squish # => "foo bar boo"
like image 476
Vijay Chouhan Avatar asked Jul 19 '13 08:07

Vijay Chouhan


1 Answers

I see no reason to (re)implement this and not use ActiveSupport, you can use it without the whole Rails framework:

require 'active_support/core_ext/string/filters'
" foo   bar    \n   \t   boo".squish
# => "foo bar baz"

Or, if you really want to avoid Rails, you could use Ruby Facets:

require 'facets/string/squish'
" foo   bar    \n   \t   boo".squish
# => "foo bar baz"


Update Well, maybe, perfomarmances could be a reason. A quick benchmark:

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)
like image 97
toro2k Avatar answered Oct 02 '22 18:10

toro2k