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"
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With