Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string to an array with spaces preserved in Ruby?

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.

like image 871
phobco Avatar asked Nov 24 '25 20:11

phobco


1 Answers

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!"]
like image 116
user1934428 Avatar answered Nov 26 '25 12:11

user1934428