How can I annotate Ruby code with its results?

by

in

People commonly annotate Ruby code by showing the results of executing each statement as a comment attached to that statement. For example, in the following code, we show that the assignment generates the string “Billy Bob”, and then the result of extracting some substrings.

str = "Billy" + " Bob"           # => "Billy Bob"
str[0,1] + str[2,1] + str[-2,2]  # => "Blob"

Emacs and vim users can integrate this with their editing environments, which is useful if you want to send people e-mail with annotated Ruby code. Having installed xmp, Emacs users can add the following to their .emacs file:

(defun ruby-xmp-region (reg-start reg-end)
  "Pipe the region through Ruby's xmp utility and replace the region with
   the result."
  (interactive "r")
  (shell-command-on-region reg-start reg-end
                           "ruby -r xmp -n -e 'xmp($_, \"%l\t\t# %r\n\")'"
                           t))
(global-set-key [(meta f10)] 'ruby-xmp-region)

Vim users can use the mapping (thanks to hipster):

map <M-F10> :!ruby -r xmp -n -e 'xmp($_, "\%l\t\t\# \%r\n")'<CR>

In both cases, highlight a region of code and hit Meta-F10 to annotate it.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *