Posted 22 days ago. Visible to the public. Repeats.

Ruby: Referencing global variables with the built-in English library

With Ruby's build-in library English you can reference global variables with an english name. This makes you code easier to read and is also suggested by Rubocop's Style/GlobalVars cop.

Example before:

Copy
if 'foo' =~ /foo/ puts $~[1] # => foo end

Example after:

Copy
if 'foo' =~ /foo/ puts $LAST_MATCH_INFO[1] # => foo end

Require pitfall in Rails

The English library is not loaded by default in Rails. So you or another library needs to require it. The chances are very high, that you application will fail in production without an explizit require e.g. when you use Rubocop or Capybara. These gems most often live in your development and/or test group of the Gemfile and require English for you.

Therefore to ensure that the library is loaded in all environments, add the following line to your config/application.rb or create an initializer like config/initializers/english.rb with the following content:

Copy
require 'English'

List of global aliases

Copy
$ERROR_INFO => $! $ERROR_POSITION => $@ $FS => $; $FIELD_SEPARATOR => $; $OFS => $, $OUTPUT_FIELD_SEPARATOR => $, $RS => $/ $INPUT_RECORD_SEPARATOR => $/ $ORS => $\ $OUTPUT_RECORD_SEPARATOR => $\ $INPUT_LINE_NUMBER => $. $NR => $. $LAST_READ_LINE => $_ $DEFAULT_OUTPUT => $> $DEFAULT_INPUT => $< $PID => $$ $PROCESS_ID => $$ $CHILD_STATUS => $? $LAST_MATCH_INFO => $~ $IGNORECASE => $= $ARGV => $* $MATCH => $& $PREMATCH => $` $POSTMATCH => $' $LAST_PAREN_MATCH => $+

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Emanuel De
Last edit:
12 days ago
by Tobias Kraze
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more