Kamilski81
Kamilski81

Reputation: 15127

How do i transform a string to become a comma separated in ruby?

I have two different string inputs:

commas = " [email protected],[email protected] , [email protected]  ,  [email protected]  "
spaces = " [email protected] [email protected]   [email protected]     [email protected]  "

And I want to create a function that produces comma separated values, and the following result:

expected = "[email protected],[email protected],[email protected],[email protected]  " 

Any suggestions? Maybe regex??

Upvotes: 0

Views: 65

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

If I understand the question correctly (to preserve spacing at the end and separate words or the like with commas only), this is one way to do it:

def modify(string)
  string.scan(/[^\s,]+/).join(',') << string[/\s+$/]
end

modify " [email protected],[email protected] , [email protected]  ,  [email protected]  "
  #=> "[email protected],[email protected],[email protected],[email protected]  "
modify " [email protected] [email protected]   [email protected]     [email protected]  "
  #=> "[email protected],[email protected],[email protected],[email protected]  "

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

Or this:

string.strip.gsub(/[ ,]+/, ',')

Note: As in your example, if you want to preserve spaces at the end of the string, you can use this (instead of strip):

string.sub(/\A +/, '').gsub(/[ ,]+(?=[^ ,])/, ',')

Upvotes: 2

Related Questions