Shortcuts and Tricks

There are three Ruby conveniences—variable modification, chained assignment, and multiple assignment—that you could live without if you really had to, but might make your life easier, and will certainly help you make your scripts smaller by adding descriptive power to little packages. Let's take a quick look at them.

Variable Modification

Almost every script will have at least a few occasions where a variable gets a new value based on its previous value. Something needs to be incremented, decremented, doubled, halved, and so forth. The conventional way to do this is to create a new value and assign it across an equals sign back to the same variable name, as follows:

 @count = @count + 1 remain = remain - 1 limit = limit * ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.