Ruby gives us six ways to complete a task when we encounter the need to invoke the operating system shell command:
1.Exec Method:
The Kernel#exec method replaces the current process example by invoking the specified command:
Copy Code code as follows:
$ IRB
>> exec ' echo ' Hello $HOSTNAME '
Hello nate.local
$
It is noteworthy that the Exec method replaces the IRB process with the echo command, thereby exiting the IRB. The main downside is that you can't know from your Ruby script whether the command was a success or failure.
2.System method
The Kernel#system Method Action command Ibid, but it is running a child shell to avoid overwriting the current process. Returns true if the command executes successfully, otherwise returns false.
Copy Code code as follows:
$ IRB
>> system ' echo ' Hello $HOSTNAME '
Hello nate.local
=> true
>> system ' false '
=> false
>> puts $?
256
=> Nil
>>
3. Inverted quotation mark (Backticks,esc key below)
Copy Code code as follows:
$ IRB
>> today = ' Date '
=> "Mon Mar 18:15:35 PDT 2007n"
>> $?
=> #<process::status:pid=25827,exited (0) >
>> $? To_i
=> 0
This is the most common use of this method. It is also running in a child shell.
4.io#popen
Copy Code code as follows:
$ IRB
>> Io.popen ("date") {|f| puts f.gets}
Mon Mar 18:58:56 PDT 2007
=> Nil
5.open3#popen3
Copy Code code as follows:
$ IRB
>> stdin, stdout, stderr = Open3.popen3 (' DC ')
=> [#<io:0x6e5474>, #<io:0x6e5438>, #<io:0x6e53d4>]
>> stdin.puts (5)
=> Nil
>> Stdin.puts (10)
=> Nil
>> stdin.puts ("+")
=> Nil
>> stdin.puts ("P")
=> Nil
>> stdout.gets
=> "15n"
6.open4#popen4
Copy Code code as follows:
$ IRB
>> require "OPEN4"
=> true
>> PID, stdin, stdout, stderr = Open4::p open4 "false"
=> [26327, #<io:0x6dff24>, #<io:0x6dfee8>, #<io:0x6dfe84>]
>> $?
=> Nil
>> PID
=> 26327
>> ignored, status = Process::waitpid2 pid
=> [26327, #<process::status:pid=26327,exited (1)]
>> status.to_i
=> 256