Don't use Ruby's Perl-style global variables
…if you can avoid it, like $: or $<. Instead, use their english aliases like $LOAD_PATH or $DEFAULT_INPUT.
One caveat: with the exception of $LOAD_PATH (an alias for $:), $LOADED_FEATURES ($") and $PROGRAM_NAME ($0), you need to require "english" before you can use the english aliases. I’d love to see english included into Ruby itself.
The English RDocs contain a list with all the available aliases.
And while we’re at it:
- Use
$stdout/$stderr/$stdininstead ofSTDOUT/STDERR/STDIN.STDOUT/STDERR/STDINare constants, and while you can actually reassign constants in Ruby, you shouldn’t. If you rely on the global variables instead, it’s much easier to redirect$stdoutto something else, for example. - Use
warninstead of$stderr.puts. That’s whatwarnis there for, after all. And it allows you to surpress warnings if you really need to (by setting the warn level to 0 via-W0). - Use
abortif you need to immediately terminate for some reason. - Use
IntegerandFloatif you need to make sure the string you’re converting actually contains an integer or a float. Observe: » “1.23”.to_f 1.23 » Float(“1.23”) 1.23 » “not a float”.to_f 0.0 » Float(“not a float”) ArgumentError: invalid value for Float(): “not a float” » “not an integer”.to_i 0 » Integer(“not an integer”) ArgumentError: invalid value for Integer(): “not an integer”
Refer to Christian Neukirchen’s Ruby Style Guide for more general info on how you can (and probably should) format your Ruby code.
(Hat-tip to @manveru, who pointed out the incorrect usage of STDOUT/STDERR/STDIN)