Ru: Ruby in Your Shell

Originally published at: http://www.sitepoint.com/ru-ruby-shell/

The venerable sed and awk are extremely powerful text-processing tools. In the hands of a master, these power tools can bend text into almost any shape and form. Unfortunately, I’m no master. More importantly, I don’t really want to invest too much time into learning sed and awk (or even bash!), especially when most of my text processing tasks are ad-hoc.

Enter Ru. Ru let’s you, the lazy Ruby programmer, to use your favourite programming language in the shell. This means that you can map, sum and capitalize to your heart’s content. In this article, we will explore some of the nifty things that Ru lets you do, and how it can simplify your text-processing tasks.

Installing Ru

Ru comes packaged as a Ruby gem. To install Ru, fire up your terminal:

% gem install ru                                                            
Successfully installed ru-0.1.4
1 gem installed

The Basics

Before we get to the good bits, let’s learn a bit about how Ru lets us use Ruby to interact with the shell. After installing the gem, we can invoke Ru with the ru command. Similar to typical Unix commands, ru reads from standard input (STDIN), as well as files.

Here’s the first example file for today’s exploration:

% cat a_tale.txt
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair…

ru can take a Ruby command and a file name as an argument:

% ru 'map(&:upcase)' a_tale.txt                                   
IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES, IT WAS THE AGE OF WISDOM, IT WAS THE AGE OF FOOLISHNESS, IT WAS THE EPOCH OF BELIEF, IT WAS THE EPOCH OF INCREDULITY, IT WAS THE SEASON OF LIGHT, IT WAS THE SEASON OF DARKNESS, IT WAS THE SPRING OF HOPE, IT WAS THE WINTER OF DESPAIR…

Continue reading this article on SitePoint

This makes me so happy.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.