Ruby: Split, then remove leading/trailing whitespace in place?

s = "one thing, two things, three things, four things"
s.split(",").map(&:strip)
# => ["one thing", "two things", "three things", "four things"]

In my Ubuntu 13.04 OS,using Ruby 2.0.0p0

require 'benchmark'

s = "one thing, two things, three things, four things"
result = ""

Benchmark.bmbm do |b|
  b.report("strip/split: ") { 1_000_000.times {result = s.split(",").map(&:strip)} }
  b.report("regex: ") { 1_000_000.times {result = s.split(/\s*,\s*/)} }
end

Rehearsal -------------------------------------------------
strip/split:    6.260000   0.000000   6.260000 (  6.276583)
regex:          7.310000   0.000000   7.310000 (  7.320001)
--------------------------------------- total: 13.570000sec

                    user     system      total        real
strip/split:    6.350000   0.000000   6.350000 (  6.363127)
regex:          7.290000   0.000000   7.290000 (  7.302163)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)