4

I'm getting a string of few lines from the shell. Is it possible to get an Array with each line being its element?

2 Answers 2

9

Sure, depending on the output you could just split it. For example:

lines = `ls`.split

This solution is independent of the method you're using to execute the program. As long as you get the complete string you can split it.

Sign up to request clarification or add additional context in comments.

Comments

6

The original question was splitting on lines, and the split function, by default, splits on white space. While that may be sufficient, you may want to pass in a regular expression, as in:

`ls -l`.split(/$/)

Which returns each line in a separate element in the array. However, it doesn't get rid of the initial carriage return or line feed. For that, you will want to use the map function to iterate over the array and apply strip to each, as in:

`ls -l`.split(/$/).map(&:strip)

2 Comments

Your method is not as good as just using "split". I test with sudo ifquery --list | grep -v lo. Yours return ["eth0", "eth1", ""], the last one is annoying.
but split doesn't work if you have '\n' in your output (as part of the name for example)

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.