-1

I have a string:

string = "Yellow.car Red.Bag Blue.eyes"

Is there a way to split the string on both periods and whitespaces, but only retain the periods inside the array?

['Yellow','.','Car','Red','.','Bag','Blue','.','Eyes']

A regex for string.split(regexp) would be preferable.

Tom
  • 1,311
  • 10
  • 18
  • https://stackoverflow.com/questions/975769/how-to-split-a-delimited-string-in-ruby-and-convert-it-to-an-array – live2 Jan 20 '19 at 18:43
  • 1
    Some readers will not like the fact that you have not quoted the string, to make it a valid Ruby object: `str = "Yellow.car Red.Bag Blue.eyes"`. Defining a variable to equal the string is not necessary, but it's convenient as it allows readers to refer to the variable in answers and comments without having to define it. In general, a variable should be set equal to each input object in examples. When asking questions it's best to avoid making assumptions about the approach to be taken (e.g., using `split`) to achieve your desired result. Just state what you want as the return value. – Cary Swoveland Jan 20 '19 at 20:01

4 Answers4

0

There is definitely a more efficient way, than this but regardless:

str = "Yellow.car Red.Bag Blue.eyes"
str.split(" ").map { |s| s.split(/([.])/) }.flatten.map(&:capitalize)
# => ["Yellow", ".", "Car", "Red", ".", "Bag", "Blue", ".", "Eyes"]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

There are many ways to do it.

For example:

str = "Yellow.car Red.Bag Blue.eyes"
str.gsub('.', ' . ').split(' ').map(&:capitalize)
#=> ["Yellow", ".", "Car", "Red", ".", "Bag", "Blue", ".", "Eyes"]

Firstly replace '.' to ' . '.

Then slice string.

And finally make first letter capital.

mechnicov
  • 12,025
  • 4
  • 33
  • 56
0

Here it's more convenient to use String#scan than String#split.

str = "Yellow.car Red.Bag Blue.eyes"

str.scan(/\p{Alpha}+|\./).map(&:capitalize)
  #=> ["Yellow", ".", "Car", "Red", ".", "Bag", "Blue", ".", "Eyes"]

The regular expression reads, "match one or more (uppercase or lowercase) letters or a period". One could substitute [[:alpha:]] for \p{Alpha}. Documentation for both (Unicode letters) are at Regexp.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

.split(/(\.)|\s+/)

When a capture group is used in String#split the match will be returned along with the split.

We will match on both periods (\.) and whitespace (\s+). Only periods will be included in the array due to the capture group ((\.)). Whitespace will still cause a split but the space itself will not be retained.

Tom
  • 1,311
  • 10
  • 18