How do I convert a String: 'Hello world!' to an array: ['Hello', ' ', 'world!'] with all spaces preserved?
I tried to convert the string using the split method with different parameters, but I didn't find the right solution.
Also I didn't find any other method in the documentation (Class: String (Ruby 3.1.0)) suitable for solving this problem.
It just occured to me, that you could use scan. Assuming that your string is stored in the variable s, and you want to separate space regions and non-space regions, you could do a
s.scan(/[ ]+|[^ ]+/)
which would yield in your case
["Hello", " ", "world!"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With