diff --git a/README.md b/README.md index 217617c..e97b60d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1218 TILs and counting..._ +_1219 TILs and counting..._ --- @@ -984,6 +984,7 @@ _1218 TILs and counting..._ - [Generate A Signed JWT Token](ruby/generate-a-signed-jwt-token.md) - [Generate Ruby Version And Gemset Files With RVM](ruby/generate-ruby-version-and-gemset-files-with-rvm.md) - [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md) +- [Get The Output Of Running A System Program](ruby/get-the-output-of-running-a-system-program.md) - [Identify Outdated Gems](ruby/identify-outdated-gems.md) - [If You Detect None](ruby/if-you-detect-none.md) - [Iterate With An Offset Index](ruby/iterate-with-an-offset-index.md) diff --git a/ruby/get-the-output-of-running-a-system-program.md b/ruby/get-the-output-of-running-a-system-program.md new file mode 100644 index 0000000..6ea11fd --- /dev/null +++ b/ruby/get-the-output-of-running-a-system-program.md @@ -0,0 +1,25 @@ +# Get The Output Of Running A System Program + +Ruby has a [variety of ways](https://stackoverflow.com/a/18623297/535590) to +execute a system program within a Ruby process. The backticks approach is the +handy shorthand approach to reach for if you want to capture the output of the +command. + +For instance, let's say I want to capture the connection string credentials +output by running a `heroku` command. When the command is wrapped in backticks, +Ruby will execute it in a subprocess and the output of the command will be the +return value. + +```ruby +result = `heroku pg:credentials:url DATABASE_URL --app my-app` + +# extract connection details +connection_info = result.split("\n")[2].strip +``` + +With the result in hand, I can use Ruby to parse out the details I'm interested +in. + +Backticks does two other nice things. It allows for string interpolation and it +puts the process status (e.g. exit code) on +[`$?`](check-return-status-of-running-a-shell-command.md).