Referencing global variables in ruby

Ruby provides a plethora of standard variables, but they can be hard to read. Using a built-in library, we can make it more obvious which variables we are referring to. Some variables such as $PROGRAM_NAME have even found their way into Ruby and are now predefined.

When I started programing with Ruby, some built-in variables were hard to read due to their brevity. For example, seeing $$ somewhere in the code was puzzling, especially without much context. Ruby provides a English library for those of us who like to be more explicit when using these variables. To explore all the aliases defined through this library, you can find the source code at ruby/lib/English.rb in the repo.

Require the library and the aliases will be available in your source.

require 'English'

# excerpt of a few available aliases:
print $$PID         # instead of $$
print $MATCH        # instead of $&
print $CHILD_STATUS # instead of $?

I know it’s fun to keep things concise and having a few less characters to type, but when collaborating on a project it may make sense to spell things out a little more. ymmv

blog comments powered by Disqus