42
things = "one thing, two things, three things, four things"

Given this input, how do I split a string by a comma and then trim the whitespace around it in place? Resulting in:

things = ["one thing", "two things", "three things", "four things"]

Currently I have this:

things = things.to_s.tr("\n\t", "").strip.split(/,/)

This does most of what I want it to do, except removing the leading/trailing whitespace when it splits on the comma. What's the best way to achieve this? I'd like to do it as part of this expression, instead of assigning the above result to a separate array and iterating over that.

2
  • What is the relation between the string "one thing, two things, three things, four things" and {:things => things.to_s.tr("\n\t", "").strip.split(/,/)}? Don't just copy exactly whatever you have. Make it into a question that people other than you can understand. Remove irrelevant things.
    – sawa
    Commented Jul 14, 2013 at 16:42
  • OK, I've done that. :-)
    – Ben
    Commented Jul 14, 2013 at 16:46

5 Answers 5

97
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)
6
  • 1
    Please note that this solution is about 2 times slower than my regex based one.
    – Koraktor
    Commented Jul 14, 2013 at 17:04
  • 1
    @Koraktor Have you actually timed it? Sometimes Ruby surprises me.
    – pjs
    Commented Jul 14, 2013 at 17:23
  • 1
    @Koraktor After benchmarking, it looks like Priti's solution runs in less than 60% of the time your regex approach requires. I replicated both 1_000_000 times using Ruby 2.0p247 on OS X. I'd be willing to post the actual benchmark code, but doing so in a comment is challenging.
    – pjs
    Commented Jul 14, 2013 at 17:58
  • 1
    I benchmarked on Ruby 1.8.7, OS X 10.8's default, so I guess you win. :)
    – Koraktor
    Commented Jul 14, 2013 at 21:46
  • 1
    Unless you are doing this operation inside of a million loops in your code, the speed differences are moot. Interesting, for sure, but likely will not matter in your code. Therefore, IMHO, the best solution is probably the one that is the most "straightforward" -- which I think is this one from Arup Rakshit
    – Jon Kern
    Commented Jun 13, 2018 at 2:01
8

Use a regular expression for #split:

"one thing, two things, three things, four things".split /\s*,\s*/
# => ["one thing", "two things", "three things", "four things"]
1
  • Just FYI, this fails the requirement if the first element has a leading space. " one thing, two things, three things, four things".split /\s*,\s*/ # => [" one thing", "two things", "three things", "four things"]
    – nafooesi
    Commented Jul 14, 2020 at 2:24
5

Not to beat a dead horse, but you can speed this up a bit more by making two changes that have become second nature to me now. The first is use map! instead of map to avoid creating a copy of the split array, and the second is to avoid use of the symbol to proc syntax (e.g. &:split, which adds an extra operation that can be avoided with the more verbose syntax).

Benchmark follows:

require 'benchmark'

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

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

Results:

                                   user     system      total        real
strip/split (map/to_proc):     5.230000   0.010000   5.240000 (  5.283079)
strip/split (map):             4.660000   0.010000   4.670000 (  4.716920)
strip/split (map!/to_proc):    4.440000   0.020000   4.460000 (  4.492943)
strip/split (map!):            4.320000   0.010000   4.330000 (  4.365386)
regex:                         7.190000   0.060000   7.250000 (  7.322932)

Remember to read the numbers relative to each other, not relative to the benchmarks provided in other answers.

2
  • Thanks for the answer, it's interesting to see a slightly more verbose syntax beating a terser one. :-)
    – Ben
    Commented Dec 23, 2013 at 1:02
  • @Ben My pleasure. Terser usually equates to more "magic", and more magic means more ops, and more ops mean slower performance :)
    – xentek
    Commented Dec 23, 2013 at 1:26
2

This is not meant as an answer to the original question, but I wanted to share benchmark code to let people check the two proposed solutions for themselves:

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

On my system (Ruby 2.0.0p247 on OS X 10.8) that produced the following output:

Rehearsal -------------------------------------------------
strip/split:    2.140000   0.000000   2.140000 (  2.143905)
regex:          3.570000   0.010000   3.580000 (  3.572911)
---------------------------------------- total: 5.720000sec

                    user     system      total        real
strip/split:    2.150000   0.000000   2.150000 (  2.146948)
regex:          3.580000   0.010000   3.590000 (  3.590646)

These results can, of course, be expected to vary between ruby versions, hardware, and OS's.

0
2

If i'm not mistaken

things.split(", ")

would be the easiest solution. However, it only works when there is exactly one space character. (Notice the space after the comma)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.