Since Ruby is scripting language, it offers different types to fire a shell command. One of them is the interpolated percentage notation. Basically the ‘%’ literal is characterized by:
- The command can be assigned as a String (or even without the String notation, meaning without quotation marks)
- Executes the command in a subshell
- Is a blocking operation (waits until the result of operation completes)
- Returns the command result
- Raises exception caused by the child process error
- The error status (exception) is available in $?, which returns a Process::Status object (with qualified exit status)
Some examples.
As a start a script.rb file is assumed. It can be found with the shell command ‘find’:
%x{find *.rb} # => "script.rb"
But if the file name has to be interpolated, it can be achieved easily:
name = 'script'
%x{find #{name}.rb} # => "script.rb"
The UNIX shell command ‘date’ returns the system time. It can be parsed into a Time object by Ruby afterwards:
Time.parse %x{date}.chop # => 2014-10-10 02:23:10 +0200
Or just watching it sleeping:
(0..4).each { |seconds| puts %x{ sleep #{seconds} && 'date'} }
An unknown command raises an error, which is returned:
%x{foo} # => Errno::ENOENT: No such file or directory - foo
and even can be processed afterwards:
%x{foo}
$? # => #<Process::Status: pid 4357 exit 127>
$?.exitstatus # => 127