rubysystemcall

Getting output of system() calls in Ruby


If I call a command using Kernel#system in Ruby, how do I get its output?

system("ls")

Solution

  • I'd like to expand & clarify chaos's answer a bit.

    If you surround your command with backticks, then you don't need to (explicitly) call system() at all. The backticks execute the command and return the output as a string. You can then assign the value to a variable like so:

    output = `ls`
    p output
    

    or

    printf output # escapes newline chars