cooltop101
cooltop101

Reputation: 79

Split string by every first space in ruby

I have a string:

"AB C   D E   F"

I need to split it into an array so that it looks like:

[AB][C][ ][D][E][ ][F]

The most I can find online is splitting by " ", which gets rid of every space, and another way that only splits by the first space in the entire string.

Upvotes: 0

Views: 1645

Answers (3)

sawa
sawa

Reputation: 168081

"AB C   D E   F".scan(/\S+|\s{2,}/)
#=> ["AB", "C", "   ", "D", "E", "   ", "F"]

Upvotes: 0

z atef
z atef

Reputation: 7679

split on spaces.

str="A B C  D E  F".split(/\s/)
#=> ["A", "B", "C", "", "D", "E", "", "F"]

or

str="A B C  D E  F".split(/\s|[a-z]/)
#=> ["A", "B", "C", "", "D", "E", "", "F"]

to prove that it works, split on spaces, join on space, and then split on spaces again. Control chars remain unaffected :)

str="A B C  D E  F".split(/\s|[a-z]/).join(" ").split(/\s|[a-z]/)
#=> ["A", "B", "C", "", "D", "E", "", "F"]

Other variations/options to explore:

str="A B C  D E  F".split(/(\s)/)
#=> ["A", " ", "B", " ", "C", " ", "", " ", "D", " ", "E", " ", "", " ", "F"]

str="A B C  D E  F".split(//)
#=> ["A", " ", "B", " ", "C", " ", " ", "D", " ", "E", " ", " ", "F"]

Upvotes: 0

Sebastián Palma
Sebastián Palma

Reputation: 33420

Maybe using scan would give you your expected output easier:

p str.scan(/[A-Z]+|\s{3}/)
# ["AB", "C", "   ", "D", "E", "   ", "F"]

As your input is only capitalized characters, [A-Z] would work, /[a-z]/i is for both cases.

Wondering why such an output:

p str.scan(/[A-Z]+|\s{3}/).map(&:split)
# [["AB"], ["C"], [], ["D"], ["E"], [], ["F"]]

Upvotes: 4

Related Questions