text
stringlengths 0
444
|
|---|
=== No Cryptic Perlisms [[no-cryptic-perlisms]]
|
Avoid using Perl-style special variables (like `$:`, `$;`, etc).
|
They are quite cryptic and their use in anything but one-liner scripts is discouraged.
|
[source,ruby]
|
----
|
# bad
|
$:.unshift File.dirname(__FILE__)
|
# good
|
$LOAD_PATH.unshift File.dirname(__FILE__)
|
----
|
Use the human-friendly aliases provided by the `English` library if required.
|
[source,ruby]
|
----
|
# bad
|
print $', $$
|
# good
|
require 'English'
|
print $POSTMATCH, $PID
|
----
|
=== Use `require_relative` whenever possible
|
For all your internal dependencies, you should use `require_relative`.
|
Use of `require` should be reserved for external dependencies
|
[source,ruby]
|
----
|
# bad
|
require 'set'
|
require 'my_gem/spec/helper'
|
require 'my_gem/lib/something'
|
# good
|
require 'set'
|
require_relative 'helper'
|
require_relative '../lib/something'
|
----
|
This way is more expressive (making clear which dependency is internal or not) and more efficient (as `require_relative` doesn't have to try all of `$LOAD_PATH` contrary to `require`).
|
=== Always Warn [[always-warn]]
|
Write `ruby -w` safe code.
|
=== No Optional Hash Params [[no-optional-hash-params]]
|
Avoid hashes as optional parameters.
|
Does the method do too much? (Object initializers are exceptions for this rule).
|
=== Instance Vars [[instance-vars]]
|
Use module instance variables instead of global variables.
|
[source,ruby]
|
----
|
# bad
|
$foo_bar = 1
|
# good
|
module Foo
|
class << self
|
attr_accessor :bar
|
end
|
end
|
Foo.bar = 1
|
----
|
=== `OptionParser` [[optionparser]]
|
Use `OptionParser` for parsing complex command line options and `ruby -s` for trivial command line options.
|
=== No Param Mutations [[no-param-mutations]]
|
Do not mutate parameters unless that is the purpose of the method.
|
=== Three is the Number Thou Shalt Count [[three-is-the-number-thou-shalt-count]]
|
Avoid more than three levels of block nesting.
|
=== Functional Code [[functional-code]]
|
Code in a functional way, avoiding mutation when that makes sense.
|
[source,ruby]
|
----
|
a = []; [1, 2, 3].each { |i| a << i * 2 } # bad
|
a = [1, 2, 3].map { |i| i * 2 } # good
|
a = {}; [1, 2, 3].each { |i| a[i] = i * 17 } # bad
|
a = [1, 2, 3].reduce({}) { |h, i| h[i] = i * 17; h } # good
|
a = [1, 2, 3].each_with_object({}) { |i, h| h[i] = i * 17 } # good
|
----
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.