kfmfe04
kfmfe04

Reputation: 15337

How to break a string into two arrays in Ruby

Is there a way to extract the strings removed by String#split into a separate array?

s = "This is a simple, uncomplicated sentence."
a = s.split( /,|\./ )  #=> [ "This is a simple", "uncomplicated sentence" ]
x = ... => should contain [ ",", "." ]

Note that the actual regex I need to use is much more complex than this example.

Upvotes: 0

Views: 83

Answers (3)

sawa
sawa

Reputation: 168269

When you want both the matched delimiters and the substrings in between as in Stefan's comment, then you should use split with captures.

"This is a simple, uncomplicated sentence."
.split(/([,.])/)
# => ["This is a simple", ",", " uncomplicated sentence", "."]

If you want to separate them into different arrays, then do:

a, x =
"This is a simple, uncomplicated sentence."
.split(/([,.])/).each_slice(2).to_a.transpose
a # => ["This is a simple", " uncomplicated sentence"]
x # => [",", "."]

or

a =
"This is a simple, uncomplicated sentence."
.split(/([,.])/)
a.select.with_index{|_, i| i.even?}
# => ["This is a simple", " uncomplicated sentence"]
a.select.with_index{|_, i| i.odd?}
# => [",", "."]

Upvotes: 1

mestachs
mestachs

Reputation: 1889

Something like this ?

a = s.scan( /,|\./ )

Upvotes: 2

munsifali
munsifali

Reputation: 1733

try this:

a = s.split(/,/)[1..-1]

Upvotes: 0

Related Questions