How to capture command line output?

I am using pry and I want to capture and work with shell command output.

For example, if I run

pry(main)> .ls 

I want to get a list of files into an array that I can work with in Ruby.

How can i do this?

+7
source share
2 answers

This is a pretty old question, but I will answer it anyway. There are two main ways to get data from pry commands. First, if the command sets the keep_retval parameter to true, which the shell command is missing. The second is to use a virtual channel. In your example, this can be done as:

 fizz = [] .ls | {|listing| fizz = listing.split("\n")} # can also be written as .ls do |listing| fizz = listing.split("\n") end 
+5
source

I suppose this is some kind of wonderful magic; -)

After a quick look at what happens (I did not look at the source of pry), you can use this:

 `ls`.split("\n") 

or

 Dir['./*'] 

What is good about this solution is that it will work outside of pry

+2
source

All Articles