In one of my previous posts I mentioned how nice it is to execute Ruby code and get the results in comments. This is quite useful when you build documentation or quickly test some ideas.
There’s one other method of doing this which is based on the Textmate’s ability to execute the code line at cursor or the selected piece of text. It’s as easy as it sounds.
- First, enter the piece of Ruby code to execute, having in mind that the result of the last line will be output below:
1 2 3
a = 2 b = 3 a * b
- Now select all three lines and press ⌃⇧E (Execute line as Ruby). The result will appear on the next line
One neat trick is that you can use printf(…) function to format your output and, in this case, the result of the last line won’t be displayed, but the printed output will.
I find it useful when there’s something to try right inside the document or there’s some formula to solve. It lets me stay where I am and not to open a separate document just for the Ruby snippet.
As a little bonus, I just want to mention that you can run unix commands in the same fashion and get the output right in your document. For example:
- Enter the following line and leave the cursor at the end of it:
ps -aux | grep nginx
- Press ⌃R (Text / Execute Line Inserting Result) to execute it. The result will be placed below.
The list of all nginx processes will be dumped. Sweet, ha.