Spawning a Process in Ruby

A good way for me to learn code-related technologies is to write unit tests.  It helps to work through the nuances, and gives me something I can go back to refresh myself as needed.

Right now, I have been going through SED, which does not have an associated unit test framework.  To test this, I want to use Ruby and then spawn a process to execute SED and then get the results back for the assert_equal call of all my tests.  I want to do this while avoiding the overhead of using files and file redirection (where possible).

I obviously can’t use Kernel::exec, as that will replace my currently running process and end my testing real quick.  I want to do the following:

     system("echo #{input_str} | #{sed_str}")

Where input_str is the input SED is processing, the sed_str is the SED command str.

Of course, I can’t do this as this is two processes being piped together.

If I use read and write files, I can do the following:

     system("#{sed_str} output.txt")

In the end, I got it to work as follows:

def sed_result(input_str, sed_str)
     %x[echo #{input_str} | #{sed_str}]

There are other options to look into – IO.pipe, IO.popen and Open3 (among others).  But I have a lot of SED unit tests to write first!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s