Bijendra
Bijendra

Reputation: 10015

Parse a string into characters using ruby

I have a requirement in my ruby code.I'm using ruby 1.9.2 and rails 3.0. I have a string like "SR2G1M1D2".Now i want to split it and extract values like [S,R2,G1,M1,D2] .It's like whenever next value is character it should split.Is there any ruby function or code available.

Thanx

Upvotes: 2

Views: 616

Answers (3)

nathanvda
nathanvda

Reputation: 50057

"SR2G1M1D2".scan(/\D\d*/)
=> ["S", "R2", "G1", "M1", "D2"] 

Hope this helps.

Upvotes: 5

d11wtq
d11wtq

Reputation: 35298

Just use #split with a RegExp:

ruby-1.9.2-p180 :002 > "SR2G1M1D2".split(/(?=[a-zA-Z])/)
 => ["S", "R2", "G1", "M1", "D2"] 
ruby-1.9.2-p180 :005 > 

Upvotes: 2

Jim Deville
Jim Deville

Reputation: 10662

split with a regex should do this. Basically a regex that does .\D with a positive lookahead on the \D. sadly i haven't used lookaheads enough to know the format

Upvotes: -1

Related Questions