I'm getting a string of few lines from the shell. Is it possible to get an Array
with each line being its element?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With