Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby execute shell command and get array

Tags:

bash

shell

ruby

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

like image 680
tolgap Avatar asked Dec 06 '22 08:12

tolgap


2 Answers

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.

like image 74
Jorge Israel Peña Avatar answered Dec 19 '22 09:12

Jorge Israel Peña


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)
like image 32
Howard Abrams Avatar answered Dec 19 '22 08:12

Howard Abrams