I have a string which will always be at least a number, but can also contain letters before and/or after the number:
"4"
"Section 2"
"4 Section"
"Section 5 Aisle"
I need to split the string like this:
"4" becomes "4"
"Section 2" becomes "Section ","2"
"4 Aisle" becomes "4"," Aisle"
"Section 5 Aisle" becomes "Section ","5"," Aisle"
How can I do this with Ruby 1.9.2?
To split a string into a list of integers: Use the str. split() method to split the string into a list of strings. Use the map() function to convert each string into an integer.
The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace.
String#split
will keep any groups from the delimiter regexp in the result array.
parts = whole.split(/(\d+)/)
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