简体   繁体   中英

Ruby - Split the string and store it in a Array based on the first word

I am pretty much new to Ruby and I am looking at the best way to do the below.

I have a string like this "Account 1 - Name, Account 1 - Age, Account 2 - Name, Account 2 - Age"

I am looking for an output something like this

[[Account 1, Name], [Account 1, Age], [Account 2, Name], [Account 2, Age]]

Certainly I don't want to post the ways I tried as it looks silly and ugly. I am looking for a single liner if possible. Many thanks and appreciate all your help!

Looks pretty straightforward. You need to split once based on , , and then again based on - . The first split already stores your data into an array for you so you don't need to do anything else.

string = "Account 1 - Name, Account 1 - Age, Account 2 - Name, Account 2 - Age"
array = string.split(', ')
array = array.map { |acc| acc.split(' - ') }
# [[Account 1, Name], [Account 1, Age], [Account 2, Name], [Account 2, Age]]

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