Kernel#system now accepts exception flag as an argument

Ruby 2.6.0-preview1 was recently released.

Using Kernel#system we can execute terminal commands. It executes commands in a subshell.

>> Kernel.system('echo atul')
atul
=> true

The method Kernel#system returns false for non zero exit status.

Ruby 2.5

puts "system method returns: #{system('bundle install')}"
➜  hello git:(master) ✗ ruby test.rb
Fetching source index from https://rubygems.org/
Could not fetch specs from https://rubygems.org/
system method returns:
false

To raise an error if the command returns false we would –

system('bundle install') || raise('Failed to execute: bundle install')
➜ hello git:(master) ✗ ruby test.rb
Fetching source index from https://rubygems.org/
Could not fetch specs from https://rubygems.org/
Traceback (most recent call last):
test.rb:1:in `<main>': Failed to execute: bundle install (RuntimeError)

Ruby 2.6.0-preview1

Since it was a common requirement, Ruby team decided to add an optional parameter to the system method. So the same can now be achieved in Ruby 2.6.0-preview1 as -

system('bundle install', exception: true)
➜  hello git:(master) ✗ ruby test.rb
Fetching source index from https://rubygems.org/
Could not fetch specs from https://rubygems.org/
Traceback (most recent call last):1: from test.rb:1:in `<main>'
test.rb:1:in `system': Command failed with exit 17: bundle
(RuntimeError)

If we specify exception flag to false, system method behaves same as it did for earlier Ruby versions i.e. the method returns false and does not raise an exception.

In Ruby 2.6.0-preview1, there is no need to raise an exception explicitly for Kernel#system method. We can specify the flag exception to true and an exception will be raised for non-zero exit status.

Comments

comments powered by Disqus