https://github.com/JuanitoFatas/ruby-style-guide
- Always run the Ruby interpreter with the
-w
option so it will warn you if you forget either of the rules below! - Use ||= freely to initialize variables.
# set name to Bozhidar, only if it's nil or false
# equivalent to name = name || 'Bozhidar'
name ||= 'Bozhidar'
- Don't use
||=
to initialize boolean variables. (Consider what would happen if the current value happened to befalse
.)
# bad - would set enabled to true even if it was false
enabled ||= true
# good
enabled = true if enabled.nil?
- Tab with 2 spaces only.
- Use spaces around operators, after commas, colons and semicolons, around
{
and before}
. - No spaces after
(
,[
or before]
,)
. - Indent
when
as deep ascase
.
# bad
case
when song.name == 'Misty'
puts 'Not again!'
when song.duration > 120
puts 'Too long!'
when Time.now.hour > 21
puts "It's too late"
else
song.play
end
# good
case
when song.name == 'Misty'
puts 'Not again!'
when song.duration > 120
puts 'Too long!'
when Time.now.hour > 21
puts "It's too late"
else
song.play
end
# good (and a bit more width efficient)
kind =
case year
when 1850..1889 then 'Blues'
when 1890..1909 then 'Ragtime'
when 1910..1929 then 'New Orleans Jazz'
when 1930..1939 then 'Swing'
when 1940..1950 then 'Bebop'
else 'Jazz'
end
- Use spaces around the
=
operator when assigning default values to method parameters:
# bad
def some_method(arg1=:default, arg2=nil, arg3=[])
# do something...
end
# good
def some_method(arg1 = :default, arg2 = nil, arg3 = [])
# do something...
end
+Add underscores to large numeric literals to improve their readability.
# bad - how many 0s are there?
num = 1000000
# good - much easier to parse for the human brain
num = 1_000_000
##Syntax
- Never use
for
, unless you know exactly why. Most of the time iterators should be used instead.for
is implemented in terms of each (so you're adding a level of indirection), but with a twist -for
doesn't introduce a new scope (unlike each) and variables defined in its block will be visible outside it.
arr = [1, 2, 3]
# bad
for elem in arr do
puts elem
end
# note that elem is accessible outside of the for loop
elem #=> 3
# good
arr.each { |elem| puts elem }
# elem is not accessible outside each's block
elem #=> NameError: undefined local variable or method `elem'
- Use one expression per branch in a ternary operator. This also means that ternary operators must not be nested. Prefer if/else constructs in these cases.
# bad
some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else
# good
if some_condition
nested_condition ? nested_something : nested_something_else
else
something_else
end
- Never use
unless
withelse
. Rewrite these with the positive case first.
# bad
unless success?
puts 'failure'
else
puts 'success'
end
# good
if success?
puts 'success'
else
puts 'failure'
end
- Favor
unless
overif
for negative conditions. - Favor
until
overwhile
for negative conditions.
# bad
do_something while !some_condition
# good
do_something until some_condition
- Use
Kernel#loop
withbreak
rather thanbegin/end/until
orbegin/end/while
for post-loop tests.
# bad
begin
puts val
val += 1
end while val < 0
# good
loop do
puts val
val += 1
break unless val < 0
end
- Omit parentheses around parameters for methods that are part of an internal DSL (e.g. Rake, Rails, RSpec), methods that have "keyword" status in Ruby (e.g. attr_reader, puts) and attribute access methods. Use parentheses around the arguments of all other method invocations.
class Person
attr_reader :name, :age
# omitted
end
temperance = Person.new('Temperance', 30)
temperance.name
puts temperance.age
x = Math.sin(y)
array.delete(e)
bowling.score.should == 0
- Omit the outer braces around an implicit options hash.
# bad
user.set({ name: 'John', age: 45, permissions: { read: true } })
# good
User.set(name: 'John', age: 45, permissions: { read: true })
- Omit both the outer braces and parentheses for methods that are part of an internal DSL.
class Person < ActiveRecord::Base
# bad
validates(:name, { presence: true, length: { within: 1..10 } })
# good
validates :name, presence: true, length: { within: 1..10 }
end
+Prefer {...}
over do...end
for single-line blocks. Avoid using {...}
for multi-line blocks (multiline chaining is always ugly). Always use do...end
for "control flow" and "method definitions" (e.g. in Rakefiles and certain DSLs). Avoid do...end
when chaining.
- As a corollary, avoid shadowing methods with local variables unless they are both equivalent.
class Foo
attr_accessor :options
# ok
def initialize(options)
self.options = options
# both options and self.options are equivalent here
end
# bad
def do_something(options = {})
unless options[:when] == :later
output(self.options[:message])
end
end
# good
def do_something(params = {})
unless params[:when] == :later
output(options[:message])
end
end
end
- Use the new lambda literal syntax for single line body blocks. Use the lambda method for multi-line blocks.
# bad
l = lambda { |a, b| a + b }
l.call(1, 2)
# correct, but looks extremely awkward
l = ->(a, b) do
tmp = a * 7
tmp * b / 50
end
# good
l = ->(a, b) { a + b }
l.call(1, 2)
l = lambda do |a, b|
tmp = a * 7
tmp * b / 50
end
- Prefer
proc
overProc.new
.
# bad
p = Proc.new { |n| puts n }
# good
p = proc { |n| puts n }
- Prefer
proc.call()
overproc[]
orproc.()
for both lambdas and procs.
# bad - looks similar to Enumeration access
l = ->(v) { puts v }
l[1]
# also bad - uncommon syntax
l = ->(v) { puts v }
l.(1)
# good
l = ->(v) { puts v }
l.call(1)
- Use
_
for unused block parameters.
# bad
result = hash.map { |k, v| v + 1 }
# good
result = hash.map { |_, v| v + 1 }
- Use
$stdout/$stderr/$stdin
instead ofSTDOUT/STDERR/STDIN
.STDOUT/STDERR/STDIN
are constants, and while you can actually reassign (possibly to redirect some stream) constants in Ruby, you'll get an interpreter warning if you do so.
STDOUT is defalut value for global $stout
-
Use warn instead of
$stderr.puts
. Apart from being more concise and clear, warn allows you to suppress warnings if you need to (by setting the warn level to 0 via -W0). -
Favor the use of
sprintf
and its alias format over the fairly crypticString#%
method.
# bad
'%d %d' % [20, 10]
# => '20 10'
# good
sprintf('%d %d', 20, 10)
# => '20 10'
# good
sprintf('%{first} %{second}', first: 20, second: 10)
# => '20 10'
format('%d %d', 20, 10)
# => '20 10'
# good
format('%{first} %{second}', first: 20, second: 10)
# => '20 10'
- Favor the use of
Array#join
over the fairly crypticArray#*
with a string argument.
# bad
%w(one two three) * ', '
# => 'one, two, three'
# good
%w(one two three).join(', ')
# => 'one, two, three'
- Use
[*var]
orArray()
instead of explicit Array check, when dealing with a variable you want to treat as an Array, but you're not certain it's an array.
# bad
paths = [paths] unless paths.is_a? Array
paths.each { |path| do_something(path) }
# good
[*paths].each { |path| do_something(path) }
# good (and a bit more readable)
Array(paths).each { |path| do_something(path) }
- Use ranges or
Comparable#between?
instead of complex comparison logic when possible.
# bad
do_something if x >= 1000 && x <= 2000
# good
do_something if (1000..2000).include?(x)
# good
do_something if x.between?(1000, 2000)
-
Avoid the use of
BEGIN
blocks. -
Never use
END
blocks. UseKernel#at_exit
instead.
# bad
END { puts 'Goodbye!' }
# good
at_exit { puts 'Goodbye!' }
- Avoid use of nested conditionals for flow of control. Prefer a guard clause when you can assert invalid data. A guard clause is a conditional statement at the top of a function that bails out as soon as it can.
# bad
def compute_thing(thing)
if thing[:foo]
update_with_bar(thing)
if thing[:foo][:bar]
partial_compute(thing)
else
re_compute(thing)
end
end
end
# good
def compute_thing(thing)
return unless thing[:foo]
update_with_bar(thing[:foo])
return re_compute(thing) unless thing[:foo][:bar]
partial_compute(thing)
end
##Naming
-
Use
snake_case
for symbols, methods and variables. -
Use
CamelCase
for classes and modules. (Keep acronyms like HTTP, RFC, XML uppercase.) -
Use
SCREAMING_SNAKE_CASE
for other constants.
# bad
SomeConst = 5
# good
SOME_CONST = 5
-
The names of predicate methods (methods that return a boolean value) should end in a question mark. (i.e.
Array#empty?
). -
The names of potentially dangerous methods (i.e. methods that modify self or the arguments,
exit!
(doesn't run the finalizers likeexit
does), etc.) should end with an exclamation mark if there exists a safe version of that dangerous method.
# bad - there is not matching 'safe' method
class Person
def update!
end
end
# good
class Person
def update
end
end
# good
class Person
def update!
end
def update
end
end
-
Define the non-bang (safe) method in terms of the bang (dangerous) one if possible.
-
When using
reduce
with short blocks, name the arguments|a, e|
(accumulator, element). -
When defining binary operators, name the argument other(
<<
and[]
are exceptions to the rule, since their semantics are different).
def +(other)
# body omitted
end
-
Prefer
map
over collect,find
overdetect
,select
overfind_all
,reduce
overinject
andsize over length
. This is not a hard requirement; if the use of the alias enhances readability, it's ok to use it. The rhyming methods are inherited from Smalltalk and are not common in other programming languages. The reason the use ofselect
is encouraged overfind_all
is that it goes together nicely withreject
and its name is pretty self-explanatory. -
Use
flat_map
instead ofmap + flatten
. This does not apply for arrays with a depth greater than 2, i.e. ifusers.first.songs == ['a', ['b','c']]
, then usemap + flatten
rather thanflat_map
.flat_map
flattens the array by 1, whereasflatten
flattens it all the way.
# bad
all_songs = users.map(&:songs).flatten.uniq
# good
all_songs = users.flat_map(&:songs).uniq
- Use
reverse_each
instead ofreverse.each
.reverse_each
doesn't do a new array allocation and that's a good thing.
##Comment
- If multiple lines are required to describe the problem, subsequent lines should be indented two spaces after the
#
.
def bar
# FIXME: This has crashed occasionally since v3.2.1. It may
# be related to the BarBazUtil upgrade.
baz(:quux)
end
-
Use
TODO
to note missing features or functionality that should be added at a later +date.+ -
Use
FIXME
to note broken code that needs to be fixed. -
Use
OPTIMIZE
to note slow or inefficient code that may cause performance problems. -
Use
HACK
to note code smells where questionable coding practices were used and should be refactored away.+ -
Use
REVIEW
to note anything that should be looked at to confirm it is working as intended. For example: REVIEW: Are we sure this is how the client does X currently?
##Classes&Modules
-
Prefer modules to classes with only class methods. Classes should be used only when it makes sense to create instances out of them.
-
Favor the use of module_function over extend
self
when you want to turn a module's instance methods into class methods.
# bad
module Utilities
extend self
def parse_something(string)
# do stuff here
end
def other_utility_method(number, string)
# do some more stuff
end
end
# good
module Utilities
module_function
def parse_something(string)
# do stuff here
end
def other_utility_method(number, string)
# do some more stuff
end
end
- Consider using
Struct.new
, which defines the trivial accessors, constructor and comparison operators for you.
# good
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
end
# better
Person = Struct.new(:first_name, :last_name) do
end
# Struct.new("Person", :first_name, :last_name)
- Consider adding factory methods to provide additional sensible ways to create instances of a particular class.
class Person
def self.create(options_hash)
# body omitted
end
end
- Prefer duck-typing over inheritance.
# bad
class Animal
# abstract method
def speak
end
end
# extend superclass
class Duck < Animal
def speak
puts 'Quack! Quack'
end
end
# extend superclass
class Dog < Animal
def speak
puts 'Bau! Bau!'
end
end
# good
class Duck
def speak
puts 'Quack! Quack'
end
end
class Dog
def speak
puts 'Bau! Bau!'
end
end
- Use def
self.method
to define singleton methods. This makes the code easier to refactor since the class name is not repeated.
class TestClass
# bad
def TestClass.some_method
# body omitted
end
# good
def self.some_other_method
# body omitted
end
# Also possible and convenient when you
# have to define many singleton methods.
class << self
def first_method
# body omitted
end
def second_method_etc
# body omitted
end
end
end
##Exceptions
##Collections
# bad
STATES = [:draft, :open, :closed]
# good
STATES = %i(draft open closed)
- Avoid the creation of huge gaps in arrays.
arr = []
arr[100] = 1 # now you have an array with lots of nils
-
Use
Set
instead ofArray
when dealing with unique elements.Set
implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup. -
Prefer symbols instead of strings as hash keys.
-
Avoid the use of mutable objects as hash keys.
-
Use
Hash#key?
instead ofHash#has_key?
andHash#value?
instead ofHash#has_value?
. As noted by Matz, the longer forms are considered deprecated. -
Use
Hash#fetch
when dealing with hash keys that should be present.
heroes = { batman: 'Bruce Wayne', superman: 'Clark Kent' }
# bad - if we make a mistake we might not spot it right away
heroes[:batman] # => "Bruce Wayne"
heroes[:supermann] # => nil
# good - fetch raises a KeyError making the problem obvious
heroes.fetch(:supermann)
- Introduce default values for hash keys via
Hash#fetch
as opposed to using custom logic.
batman = { name: 'Bruce Wayne', is_evil: false }
# bad - if we just use || operator with falsy value we won't get the expected result
batman[:is_evil] || true # => true
# good - fetch work correctly with falsy values
batman.fetch(:is_evil, true) # => false
- Prefer the use of the block instead of the default value in
Hash#fetch
.
batman = { name: 'Bruce Wayne' }
# bad - if we use the default value, we eager evaluate it
# so it can slow the program down if done multiple times
batman.fetch(:powers, get_batman_powers) # get_batman_powers is an expensive call
# good - blocks are lazy evaluated, so only triggered in case of KeyError exception
batman.fetch(:powers) { get_batman_powers }
- Never modify a collection while traversing it.
##String
-
Prefer single-quoted strings when you don't need string interpolation or special symbols such as
\t, \n, ',
etc. -
Avoid using
String#+
when you need to construct large data chunks. Instead, useString#<<
. Concatenation mutates the string instance in-place and is always faster thanString#+
, which creates a bunch of new string objects.
# good and also fast
html = ''
html << '<h1>Page title</h1>'
paragraphs.each do |paragraph|
html << "<p>#{paragraph}</p>"
end
- When using heredocs for multi-line strings keep in mind the fact that they preserve leading whitespace. It's a good practice to employ some margin based on which to trim the excessive whitespace.
code = <<-END.gsub(/^\s+\|/, '')
|def test
| some_method
| other_method
|end
END
#=> "def\n some_method\n \nother_method\nend"
##Regular Expressions
-
Don't use regular expressions if you just need plain text search in string:
string['text']
-
Use non-capturing groups when you don't use captured result of parentheses.
/(first|second)/ # bad
/(?:first|second)/ # good
- Be careful with
^
and$
as they match start/end of line, not string endings. If you want to match the whole string use:\A
and\z
(not to be confused with\Z
which is the equivalent of/\n?\z/
).
string = "some injection\nusername"
string[/^username$/] # matches
string[/\Ausername\z/] # don't match
- Use
x
modifier for complex regexps. This makes them more readable and you can add some useful comments. Just be careful as spaces are ignored.
regexp = %r{
start # some text
\s # white space char
(group) # first group
(?:alt1|alt2) # some alternation
end
}x
- For complex replacements
sub/gsub
can be used with block or hash.
##Percent Literals
- Use
%()
(it's a shorthand for%Q
) for single-line strings which require both interpolation and embedded double-quotes. For multi-line strings, prefer heredocs.
# bad (no interpolation needed)
%(<div class="text">Some text</div>)
# should be '<div class="text">Some text</div>'
# bad (no double-quotes)
%(This is #{quality} style)
# should be "This is #{quality} style"
# bad (multiple lines)
%(<div>\n<span class="big">#{exclamation}</span>\n</div>)
# should be a heredoc.
# good (requires interpolation, has quotes, single line)
%(<tr><td class="name">#{name}</td>)
- Avoid
%q
unless you have a string with both'
and"
in it. Regular string literals are more readable and should be preferred unless a lot of characters would have to be escaped in them.
# bad
name = %q(Bruce Wayne)
time = %q(8 o'clock)
question = %q("What did you say?")
# good
name = 'Bruce Wayne'
time = "8 o'clock"
question = '"What did you say?"'
- Use
%r
only for regular expressions matching more than one'/'
character.
# bad
%r(\s+)
# still bad
%r(^/(.*)$)
# should be /^\/(.*)$/
# good
%r(^/blog/2011/(.*)$)
-
Avoid the use of
%s
. It seems that the community has decided:"some string"
is the preferred way to created a symbol with spaces in it. -
Prefer
()
as delimiters for all%
literals, except%r
. Since braces often appear inside regular expressions in many scenarios a less common character like { might be a better choice for a delimiter, depending on the regexp's content.
# bad
%w[one two three]
%q{"Test's king!", John said.}
# good
%w(one tho three)
%q("Test's king!", John said.)
##Metaprogramming
##Misc