How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?
The answers above are already quite great, but I really want to share the following summary article: "6 Ways to Run Shell Commands in Ruby"
Basically, it tells us:
Kernel#exec
:
exec 'echo "hello $HOSTNAME"'
system
and $?
:
system 'false'
puts $?
Backticks (`):
today = `date`
IO#popen
:
IO.popen("date") { |f| puts f.gets }
Open3#popen3
-- stdlib:
require "open3"
stdin, stdout, stderr = Open3.popen3('dc')
Open4#popen4
-- a gem:
require "open4"
pid, stdin, stdout, stderr = Open4::popen4 "false" # => [26327, #, #, #]