Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 839
Ben Avatar asked Jul 14 '13 16:07

Ben


People also ask

How do you remove leading and trailing spaces in Ruby?

Ruby has lstrip and rstrip methods which can be used to remove leading and trailing whitespaces respectively from a string. Ruby also has strip method which is a combination of lstrip and rstrip and can be used to remove both, leading and trailing whitespaces, from a string.

How do you get rid of leading and trailing white spaces?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do you remove white spaces in Ruby?

If you want to remove only leading and trailing whitespace (like PHP's trim) you can use . strip , but if you want to remove all whitespace, you can use . gsub(/\s+/, "") instead .

What does .split do in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.


1 Answers

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) 
like image 51
Arup Rakshit Avatar answered Sep 20 '22 15:09

Arup Rakshit