0

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!

1
  • 1
    @Joseph gives the normal solution, but you could also write str.split(/ - |, /).each_slice(2).to_a. str.split(/ - |, /) #=> ["Account 1", "Name", "Account 1", "Age", "Account 2", "Name", "Account 2", "Age"]. See Enumerable#each_slice (the "no block given" case). Commented May 22, 2020 at 18:17

1 Answer 1

3

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

Cool. Thank you so much! Since I am new to Ruby, I was not aware of the map method. May be I missed reading the document or it did not strike me when I went through the docs. Got to know about it now!
@shank087 sure thing! I edited my answer you gotta reassign array if you don't use map!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.