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.[link]

    1. arr = [1, 2, 3]
    2. # bad
    3. for elem in arr do
    4. puts elem
    5. end
    6. # good
    7. arr.each { |elem| puts elem }
  • 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.[link]

    1. names = ["Bozhidar", "Steve", "Sarah"]
    2. # good
    3. names.each { |name| puts name }
    4. # bad
    5. names.each do |name| puts name end
    6. # good
    7. names.each do |name|
    8. puts name
    9. puts 'yay!'
    10. end
    11. # bad
    12. names.each { |name|
    13. puts name
    14. puts 'yay!'
    15. }
    16. # good
    17. names.select { |name| name.start_with?("S") }.map { |name| name.upcase }
    18. # bad
    19. names.select do |name|
    20. name.start_with?("S")
    21. end.map { |name| name.upcase }

    Some will argue that multiline chaining would look okay with the use of
    {...}, but they should ask themselves if this code is really readable and
    whether the block’s content can be extracted into nifty methods.

  • Use shorthand self assignment operators
    whenever applicable.[link]

    1. # bad
    2. x = x + y
    3. x = x * y
    4. x = x**y
    5. x = x / y
    6. x = x || y
    7. x = x && y
    8. # good
    9. x += y
    10. x *= y
    11. x **= y
    12. x /= y
    13. x ||= y
    14. x &&= y
  • Avoid semicolons except for in single line class
    definitions. When it is appropriate to use a semicolon, it should be
    directly adjacent to the statement it terminates: there should be no
    space before the semicolon.[link]

    1. # bad
    2. puts 'foobar'; # superfluous semicolon
    3. puts 'foo'; puts 'bar' # two expressions on the same line
    4. # good
    5. puts 'foobar'
    6. puts 'foo'
    7. puts 'bar'
    8. puts 'foo', 'bar' # this applies to puts in particular
  • Use :: only to reference constants(this includes
    classes and modules) and constructors (like Array() or Nokogiri::HTML()).
    Do not use :: for regular method invocation.[link]

    1. # bad
    2. SomeClass::some_method
    3. some_object::some_method
    4. # good
    5. SomeClass.some_method
    6. some_object.some_method
    7. SomeModule::SomeClass::SOME_CONST
    8. SomeModule::SomeClass()
  • Avoid return where not required.
    [link]

    1. # bad
    2. def some_method(some_arr)
    3. return some_arr.size
    4. end
    5. # good
    6. def some_method(some_arr)
    7. some_arr.size
    8. end
  • Don’t use the return value of = in
    conditionals[link]

    1. # bad - shows intended use of assignment
    2. if (v = array.grep(/foo/))
    3. ...
    4. end
    5. # bad
    6. if v = array.grep(/foo/)
    7. ...
    8. end
    9. # good
    10. v = array.grep(/foo/)
    11. if v
    12. ...
    13. end
  • Use ||= freely to initialize variables.
    [link]

    1. # set name to Bozhidar, only if it's nil or false
    2. name ||= 'Bozhidar'
  • Don’t use ||= to initialize boolean
    variables. (Consider what would happen if the current value happened to be
    false.)[link]

    1. # bad - would set enabled to true even if it was false
    2. enabled ||= true
    3. # good
    4. enabled = true if enabled.nil?
  • Use .call explicitly when calling lambdas.
    [link]

    1. # bad
    2. lambda.(x, y)
    3. # good
    4. lambda.call(x, y)
  • Avoid using Perl-style special variables (like
    $0-9, $, etc. ). They are quite cryptic and their use in anything but
    one-liner scripts is discouraged. Prefer long form versions such as
    $PROGRAM_NAME.[link]

  • When a method block takes only one
    argument, and the body consists solely of reading an attribute or calling
    one method with no arguments, use the &: shorthand.
    [link]

    1. # bad
    2. bluths.map { |bluth| bluth.occupation }
    3. bluths.select { |bluth| bluth.blue_self? }
    4. # good
    5. bluths.map(&:occupation)
    6. bluths.select(&:blue_self?)
  • Prefer some_method over self.some_method when
    calling a method on the current instance.[link]

    1. # bad
    2. def end_date
    3. self.start_date + self.nights
    4. end
    5. # good
    6. def end_date
    7. start_date + nights
    8. end

    In the following three common cases, self. is required by the language
    and is good to use:

    1. When defining a class method: def self.some_method.
    2. The left hand side when calling an assignment method, including assigning
      an attribute when self is an ActiveRecord model: self.guest = user.
    3. Referencing the current instance’s class: self.class.
  • When defining an object of any mutable
    type meant to be a constant, make sure to call freeze on it. Common
    examples are strings, arrays, and hashes.
    ([More on this][ruby-freeze].)[link]

    The reason is that Ruby constants are actually mutable. Calling freeze
    ensures they are not mutated and are therefore truly constant and
    attempting to modify them will raise an exception. For strings, this allows
    older versions of Ruby below 2.2 to intern them.

    1. # bad
    2. class Color
    3. RED = 'red'
    4. BLUE = 'blue'
    5. GREEN = 'green'
    6. ALL_COLORS = [
    7. RED,
    8. BLUE,
    9. GREEN,
    10. ]
    11. COLOR_TO_RGB = {
    12. RED => 0xFF0000,
    13. BLUE => 0x0000FF,
    14. GREEN => 0x00FF00,
    15. }
    16. end
    17. # good
    18. class Color
    19. RED = 'red'.freeze
    20. BLUE = 'blue'.freeze
    21. GREEN = 'green'.freeze
    22. ALL_COLORS = [
    23. RED,
    24. BLUE,
    25. GREEN,
    26. ].freeze
    27. COLOR_TO_RGB = {
    28. RED => 0xFF0000,
    29. BLUE => 0x0000FF,
    30. GREEN => 0x00FF00,
    31. }.freeze
    32. end