R2-D2's_Father
R2-D2's_Father

Reputation: 173

Replace string characters with a single comma

I want to remove unwanted symbols from this string:

myString = String.new("@@106#107#Hello@@106#World@@")

and separate each word with a comma. The desired result is:

"Hello, World"

Any ideas on how to achieve my desired result? What I tried is this:

myString.gsub!(/[@#0123456789]/, ',')
print myString + "\n"
# => ",,,,,,,,,,Hello,,,,,,World,,"

Upvotes: 1

Views: 74

Answers (2)

sawa
sawa

Reputation: 168209

myString.gsub(/(\A)?[^a-zA-Z]+(\z)?/){$1 || $2 ? "" : ", "}
# => "Hello, World"

Upvotes: 3

ichigolas
ichigolas

Reputation: 7735

There are a couple of ways:

myString.scan(/[a-zA-Z]+/).join(', ')
=> "Hello, World"

Upvotes: 4

Related Questions