Grepping from Ruby

I recently needed to run through one data file, pull a number, and look that number up in several other data files. So in Ruby, I first opened the initial file, pulled the number, and then opened the other files, iterating through every line until I found a match, then call break to move on. This worked, but it was sort of slow.

It occurred to me that I could use grep to see if the number was in the other files. So I had to figure out how to call it from Ruby. Here’s what I came up with:

The speed improvement depends on how many searches you’re doing and the size of the files you’re searching, but in a quick test the grep calls were 5x faster.