简体   繁体   中英

Get list of items from a string in Ruby

I have the following string which I need to parse with Ruby:

Long description text which could have multiple returns.

This is the final line of the description.
~
1. This is step 1

2. And this is step 2

3. There could be an infinite number of steps

4. But this is the last step

I'd like to split out everything before the list of steps into a string, and then have an array of steps.

In Objective-C, I'd do this using ranges and a while loop until it can't find anymore steps.

I'm thinking there may be something smarter in Ruby, but I haven't been able to find anything.

I'd do using split and scan :

string = <<EOS
Long description text which could have multiple returns.
This is the final line of the description.
~
1. This is step 1
2. And this is step 2
3. There could be an infinite number of steps
4. But this is the last step
EOS

description, list_text = string.split('~')
list = list_text.scan(/^\d+.*$/)

puts description
# Long description text which could have multiple returns.
# This is the final line of the description.

p list
# ["1. This is step 1", "2. And this is step 2", 
#  "3. There could be an infinite number of steps", 
#  "4. But this is the last step"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM