Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create array from some string from text file – Ruby

I’m trying to create array from string from text file.

For example in txt file I have string.

"ABC;DEF;GHI"

I want to create array which looks like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["ABC","DEF","GHI"]

I have tried that using method below:

File.open(file.txt).map { |line| line.split(/;/) }

but output of the above method was:

[["ABC","DEF","GHI"]]

You may notice that this is an array within an array.

What I should to do?

>Solution :

Use flat_map instead of map

Code

File.open(file.txt).flat_map{ |line| line.split(/;/) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading