ruby -run
Post image
Image by starline on Freepik

This is a loose translation of my post from 2017

Recently, I was looking for a one-liner to start a web-server in the current directory. Stack Overflow gave me this command:

ruby -run -e httpd -- -p 9090 [DIR]

So what is this mysterious -run option an why is it not in the ruby manual?

Option -run

In reality, -run is not an option. More precisely, it’s an option, but not “run”. Notice that there’s one dash instead of two.

Turns out, it’s just an option -r with an argument un. And un is a file in ruby standard library (2023 edit: now available on Github). It defines a few useful methods to use in one-liners as standalone programs.

One of the methods is httpd which just start WebBrick with parameters from ARGV (in the case above, it’s just port and directory).

Availability

Apparently, it’s a really old file beceause I found its documentation for ruby 1.8.6. So you can use it freely.

What else is in there?

Here’s a copypaste from the docs:

ruby -run -e cp -- [OPTION] SOURCE DEST
ruby -run -e ln -- [OPTION] TARGET LINK_NAME
ruby -run -e mv -- [OPTION] SOURCE DEST
ruby -run -e rm -- [OPTION] FILE
ruby -run -e mkdir -- [OPTION] DIRS
ruby -run -e rmdir -- [OPTION] DIRS
ruby -run -e install -- [OPTION] SOURCE DEST
ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE
ruby -run -e touch -- [OPTION] FILE
ruby -run -e help [COMMAND]

Outro

I think there’s not much point in using un outside of one-liners since its every method uses ARGV but it’s useful to remember that ruby has it. I imagine it’ll work in Windows too bringing a way to use Unix-tools in it.

BTW, I added this alias to my bash config:

alias start-webrick='ruby -run -e httpd -- -p 9090'

Really convenient!