Last Updated: February 25, 2016
· manewitz

Numbered List Ruby One-Liner

Quick Numbered List Ruby Shortcut

I make a lot of todo lists and so I wrote a quick one-liner to do it for me and added it to my file. It's pipe-friendly so you can send it to your editor of choice (see usage below).

function list() {
  ruby -e "list= *(1..$1); puts list * %Q{. \n} + '. '"


> list 5
> list 7 | vim
> list 10 | mate

Line by line:

ruby -e 

-e is a flag for Ruby that executes the following code (quoted in this case)

list = *(1..$1) 

Create a Range object from 1 to $1, which is a variable bash has assigned to your first command line argument (next would be $2, $3, etc.)

The asterisk ensures that the object returned will be an Array, even if it's a single object. This only works during assignment, ie *(1) doesn't work, but n = *(1) does.

puts list * %Q{. \n} + '. ' 

In the Array class, the * operator can be passed a string as an argument, which will join adjacent Array elements together. In this case, I'm using a period, a space and a newline character. I'm using the %{ } syntax since I'm double-quoting the entire ruby -e command and it will let me use unescaped backslashes. Finally, I manually add the ". ", which isn't produced by Array#join.

It's quite simple, but I got a chance to use a few Ruby tricks I hadn't before that have come in useful in general coding.



2 Responses
Add your response

You don't need ruby

function list() { seq $1 | while read n; do echo "${n}. "; done }

over 1 year ago ·

Bash is by far the cleaner way of doing this. My alias file now has the following:

function list() { seq -s ".\n" $1 }

over 1 year ago ·