I’m trying to think of some useful Ruby snippets. If you’ve got any ideas, folks, please let me know!
Snippets are those auto-expansion thingummies that you can plonk into the Visual Studio code editor either by selecting them from a popup menu or by entering a few characters as a shortcut and pressing the Tab key. Most snippets have one or more highlighted ‘replacement points’ into which you can enter some text – say, the name of a variable – and, in some cases, this name will automatically ‘propagate’ to other parts of the snippet. Here, for example, is a Ruby get/set snippet. I start this off by entering its shortcut, ‘getset’, into the editor:
getset
Then I press the Tab key and, hey presto, it expands into a block of code which, in this case, happens to be a pair of getter and setter methods.
The snippet has two highlighted ‘replacement points’ with ‘placeholder’ text: name and aName. The first of these, name, is the more interesting as it occurs as part of the two method names get_name and set_name and also as part of the instance variable name, @name . In fact, I want to rename the methods to get_val and set_val while I want the instance variable to be called @val .
That’s easy to do. I just edit the first replacement point, changing the placeholder text name to my desired identifier, val. Having done that, I press Tab to move to the next replacement point, aName and, as I do so, all the occurrences of the original name are automatically changed to val.
Snippets can, in principle, of course, be much longer and more complex than this one. I love timesavers like this when I’m coding - which is why I was very keen to get snippets into Ruby In Steel.
Visual Studio Snippets are saved in XML format and, while they can be edited by hand, I personally don’t find writing hand-coded XML sufficiently entertaining to want to do it on a regular basis. Which explains why I have recently been programming a snippet editor (called Sniped!) for Ruby In Steel. This will let you create snippets just by filling in some text fields. So far I’ve created the obvious Ruby snippets – begin..until, begin..while, if, if..else and so forth. If you have any ideas for other candidates for self-expanding Ruby code snippets, please say…