[
  {
    "path": ".circleci/config.yml",
    "content": "version: 2\n\njobs:\n  docs-build:\n    docker:\n      - image: ruby:2.6\n    steps:\n      - checkout\n      - run:\n          name: Install AsciiDoctor & Rouge\n          command: |\n            gem install asciidoctor\n            gem install rouge -v 3.3.0\n      - run:\n          name: Build Site\n          command: asciidoctor -a toc=\"left\" -a toclevels=2 README.adoc -o _build/html/index.html\n      - persist_to_workspace:\n          root: _build\n          paths: html\n  docs-deploy:\n    docker:\n      - image: node:8.10.0\n    steps:\n      - checkout\n      - attach_workspace:\n          at: _build\n      - run:\n          name: Disable jekyll builds\n          command: touch _build/html/.nojekyll\n      - run:\n          name: Install and configure dependencies\n          command: |\n            npm install -g --silent gh-pages@2.0.1\n            git config user.email \"ci-build@rubystyle.guide\"\n            git config user.name \"ci-build\"\n      - add_ssh_keys:\n          fingerprints:\n            - \"ea:f9:10:fa:c9:1c:7d:cd:f9:21:37:bf:a8:ee:b9:c9\"\n      - run:\n          name: Deploy docs to gh-pages branch\n          command: gh-pages -add --dotfiles --message \"[skip ci] Update site\" --dist _build/html\n\nworkflows:\n  version: 2\n  build:\n    jobs:\n      - docs-build\n      - docs-deploy:\n          requires:\n            - docs-build\n          filters:\n            branches:\n              only: master\n"
  },
  {
    "path": ".gitattributes",
    "content": "*.adoc whitespace=trailing-space,tab-in-indent\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: 'github-actions'\n    directory: '/'\n    schedule:\n      interval: 'weekly'\n"
  },
  {
    "path": ".github/workflows/spell_checking.yml",
    "content": "name: Spell Checking\n\non: [pull_request]\n\njobs:\n  codespell:\n    name: Check spelling with codespell\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        python-version: [3.8]\n    steps:\n      - uses: actions/checkout@v6\n      - name: Set up Python ${{ matrix.python-version }}\n        uses: actions/setup-python@v6\n        with:\n          python-version: ${{ matrix.python-version }}\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip\n          pip install codespell\n          if [ -f requirements.txt ]; then pip install -r requirements.txt; fi\n      - name: Check spelling with codespell\n        run: codespell --ignore-words=codespell.txt || exit 1\n  misspell:\n    name: Check spelling with misspell\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v6\n      - name: Install\n        run: wget -O - -q https://raw.githubusercontent.com/client9/misspell/master/install-misspell.sh | sh -s -- -b .\n      - name: Misspell\n        run: ./misspell -error\n"
  },
  {
    "path": ".gitignore",
    "content": "README.html\nREADME.pdf\n"
  },
  {
    "path": "README.adoc",
    "content": "= Ruby Style Guide\n:idprefix:\n:idseparator: -\n:sectanchors:\n:sectlinks:\n:toc: preamble\n:toclevels: 1\nifndef::backend-pdf[]\n:toc-title: pass:[<h2>Table of Contents</h2>]\nendif::[]\n:source-highlighter: rouge\n\n== Introduction\n\n[quote, Officer Alex J. Murphy / RoboCop]\n____\nRole models are important.\n____\n\nifdef::env-github[]\nTIP: You can find a beautiful version of this guide with much improved navigation at https://rubystyle.guide.\nendif::[]\n\nThis Ruby style guide recommends best practices so that real-world Ruby programmers can write code that can be maintained by other real-world Ruby programmers.\nA style guide that reflects real-world usage gets used, while a style guide that holds to an ideal that has been rejected by the people it is supposed to help risks not getting used at all - no matter how good it is.\n\nThe guide is separated into several sections of related guidelines.\nWe've tried to add the rationale behind the guidelines (if it's omitted we've assumed it's pretty obvious).\n\nWe didn't come up with all the guidelines out of nowhere - they are mostly based on the professional experience of the editors, feedback and suggestions from members of the Ruby community and various highly regarded Ruby programming resources, such as https://pragprog.com/book/ruby4/programming-ruby-1-9-2-0[\"Programming Ruby\"] and https://www.amazon.com/Ruby-Programming-Language-David-Flanagan/dp/0596516177[\"The Ruby Programming Language\"].\n\nThis style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in Ruby itself.\n\nifdef::env-github[]\nYou can generate a PDF copy of this guide using https://asciidoctor.org/docs/asciidoctor-pdf/[AsciiDoctor PDF], and an HTML copy https://asciidoctor.org/docs/convert-documents/#converting-a-document-to-html[with] https://asciidoctor.org/#installation[AsciiDoctor] using the following commands:\n\n[source,console]\n----\n# Generates README.pdf\nasciidoctor-pdf -a allow-uri-read README.adoc\n\n# Generates README.html\nasciidoctor README.adoc\n----\n\n[TIP]\n====\nInstall the `rouge` gem to get nice syntax highlighting in the generated document.\n\n[source,console]\n----\ngem install rouge\n----\n====\nendif::[]\n\n[TIP]\n====\nIf you're into Rails or RSpec you might want to check out the complementary https://github.com/rubocop/rails-style-guide[Ruby on Rails Style Guide] and https://github.com/rubocop/rspec-style-guide[RSpec Style Guide].\n====\n\nTIP: https://github.com/rubocop/rubocop[RuboCop] is a static code analyzer (linter) and formatter, based on this style guide.\n\n=== Guiding Principles\n\n[quote, Harold Abelson, Structure and Interpretation of Computer Programs]\n____\nPrograms must be written for people to read, and only incidentally for machines to execute.\n____\n\nIt's common knowledge that code is read much more often than it is written.\nThe guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Ruby code.\nThey are also meant to reflect real-world usage of Ruby instead of a random ideal. When we had to choose between a very established practice\nand a subjectively better alternative we've opted to recommend the established practice.footnote:[Occasionally we might suggest to the reader to consider some alternatives, though.]\n\nThere are some areas in which there is no clear consensus in the Ruby community regarding a particular style (like string literal quoting, spacing inside hash literals, dot position in multi-line method chaining, etc.).\nIn such scenarios all popular styles are acknowledged and it's up to you to pick one and apply it consistently.\n\nRuby had existed for over 15 years by the time\nthe guide was created, and the language's flexibility and lack of common standards have contributed to the\ncreation of numerous styles for just about everything. Rallying people around the cause of community standards\ntook a lot of time and energy, and we still have a lot of ground to cover.\n\nRuby is famously optimized for programmer happiness. We'd like to believe that this guide is going to help you optimize for maximum\nprogrammer happiness.\n\n=== A Note about Consistency\n\n[quote, Ralph Waldo Emerson]\n____\nA foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines.\n____\n\nA style guide is about consistency.\nConsistency with this style guide is important.\nConsistency within a project is more important.\nConsistency within one class or method is the most important.\n\nHowever, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment.\nLook at other examples and decide what looks best. And don't hesitate to ask!\n\nIn particular: do not break backwards compatibility just to comply with this guide!\n\nSome other good reasons to ignore a particular guideline:\n\n* When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this style guide.\n* To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style).\n* Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.\n* When the code needs to remain compatible with older versions of Ruby that don't support the feature recommended by the style guide.\n\n=== Translations\n\nTranslations of the guide are available in the following languages:\n\n* https://github.com/JuanitoFatas/ruby-style-guide/blob/master/README-zhCN.md[Chinese Simplified]\n* https://github.com/JuanitoFatas/ruby-style-guide/blob/master/README-zhTW.md[Chinese Traditional]\n* https://github.com/HassanTC/ruby-style-guide/blob/master/README-EgAr.md[Egyptian Arabic]\n* https://github.com/gauthier-delacroix/ruby-style-guide/blob/master/README-frFR.md[French]\n* https://github.com/fortissimo1997/ruby-style-guide/blob/japanese/README.ja.md[Japanese]\n* https://github.com/dalzony/ruby-style-guide/blob/master/README-koKR.md[Korean]\n* https://github.com/rubensmabueno/ruby-style-guide/blob/master/README-PT-BR.md[Portuguese (pt-BR)]\n* https://github.com/arbox/ruby-style-guide/blob/master/README-ruRU.md[Russian]\n* https://github.com/alemohamad/ruby-style-guide/blob/master/README-esLA.md[Spanish]\n* https://github.com/CQBinh/ruby-style-guide/blob/master/README-viVN.md[Vietnamese]\n\nNOTE: These translations are not maintained by our editor team, so their quality\nand level of completeness may vary. The translated versions of the guide often\nlag behind the upstream English version.\n\n== Source Code Layout\n\n[quote, Jerry Coffin (on indentation)]\n____\nNearly everybody is convinced that every style but their own is\nugly and unreadable. Leave out the \"but their own\" and they're\nprobably right...\n____\n\n=== Source Encoding [[utf-8]]\n\nUse `UTF-8` as the source file encoding.\n\nTIP: UTF-8 has been the default source file encoding since Ruby 2.0.\n\n=== Tabs or Spaces? [[tabs-or-spaces]]\n\nUse only spaces for indentation. No hard tabs.\n\n=== Indentation [[spaces-indentation]]\n\nUse two *spaces* per indentation level (aka soft tabs).\n\n[source,ruby]\n----\n# bad - four spaces\ndef some_method\n    do_something\nend\n\n# good\ndef some_method\n  do_something\nend\n----\n\n=== Maximum Line Length [[max-line-length]]\n\nLimit lines to 80 characters.\n\nTIP: Most editors and IDEs have configuration options to help you with that.\nThey would typically highlight lines that exceed the length limit.\n\n.Why Bother with 80 characters in a World of Modern Widescreen Displays?\n****\n\nA lot of people these days feel that a maximum line length of 80 characters is\njust a remnant of the past and makes little sense today. After all - modern\ndisplays can easily fit 200+ characters on a single line.  Still, there are some\nimportant benefits to be gained from sticking to shorter lines of code.\n\nFirst, and foremost - numerous studies have shown that humans read much faster\nvertically and very long lines of text impede the reading process. As noted\nearlier, one of the guiding principles of this style guide is to optimize the\ncode we write for human consumption.\n\nAdditionally, limiting the required editor window width makes it possible to\nhave several files open side-by-side, and works well when using code review\ntools that present the two versions in adjacent columns.\n\nThe default wrapping in most tools disrupts the visual structure of the code,\nmaking it more difficult to understand. The limits are chosen to avoid wrapping\nin editors with the window width set to 80, even if the tool places a marker\nglyph in the final column when wrapping lines. Some web based tools may not\noffer dynamic line wrapping at all.\n\nSome teams strongly prefer a longer line length. For code maintained exclusively\nor primarily by a team that can reach agreement on this issue, it is okay to\nincrease the line length limit up to 100 characters, or all the way up\nto 120 characters. Please, restrain the urge to go beyond 120 characters.\n****\n\n=== No Trailing Whitespace [[no-trailing-whitespace]]\n\nAvoid trailing whitespace.\n\nTIP: Most editors and IDEs have configuration options to visualize trailing whitespace and\nto remove it automatically on save.\n\n=== Line Endings [[crlf]]\n\nUse Unix-style line endings.footnote:[*BSD/Solaris/Linux/macOS users are covered by default, Windows users have to be extra careful.]\n\n[TIP]\n====\nIf you're using Git you might want to add the following configuration setting to protect your project from Windows line endings creeping in:\n\n[source,console]\n----\n$ git config --global core.autocrlf true\n----\n====\n\n=== Should I Terminate Files with a Newline? [[newline-eof]]\n\nEnd each file with a newline.\n\nTIP: This should be done via editor configuration, not manually.\n\n=== Should I Terminate Expressions with `;`? [[no-semicolon]]\n\nDon't use `;` to terminate statements and expressions.\n\n[source,ruby]\n----\n# bad\nputs 'foobar'; # superfluous semicolon\n\n# good\nputs 'foobar'\n----\n\n=== One Expression Per Line [[one-expression-per-line]]\n\nUse one expression per line.\n\n[source,ruby]\n----\n# bad\nputs 'foo'; puts 'bar' # two expressions on the same line\n\n# good\nputs 'foo'\nputs 'bar'\n\nputs 'foo', 'bar' # this applies to puts in particular\n----\n\n=== Operator Method Call\n\nAvoid dot where not required for operator method calls.\n\n[source,ruby]\n----\n# bad\nnum.+ 42\n\n# good\nnum + 42\n----\n\n=== Spaces and Operators [[spaces-operators]]\n\nUse spaces around operators, after commas, colons and semicolons.\nWhitespace might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code.\n\n[source,ruby]\n----\n# bad\nsum=1+2\na,b=1,2\nclass FooError<StandardError;end\n\n# good\nsum = 1 + 2\na, b = 1, 2\nclass FooError < StandardError; end\n----\n\nThere are a few exceptions:\n\n* Exponent operator:\n\n[source,ruby]\n----\n# bad\ne = M * c ** 2\n\n# good\ne = M * c**2\n----\n\n* Slash in rational literals:\n\n[source,ruby]\n----\n# bad\no_scale = 1 / 48r\n\n# good\no_scale = 1/48r\n----\n\n* Safe navigation operator:\n\n[source,ruby]\n----\n# bad\nfoo &. bar\nfoo &.bar\nfoo&. bar\n\n# good\nfoo&.bar\n----\n\n=== Safe navigation\n\nAvoid long chains of `&.`. The longer the chain is, the harder it becomes to track what\non it could be returning a `nil`. Replace with `.` and an explicit check.\nE.g. if users are guaranteed to have an address and addresses are guaranteed to have a zip code:\n\n[source,ruby]\n----\n# bad\nuser&.address&.zip&.upcase\n\n# good\nuser && user.address.zip.upcase\n----\n\nIf such a change introduces excessive conditional logic, consider other approaches, such as delegation:\n[source,ruby]\n----\n# bad\nuser && user.address && user.address.zip && user.address.zip.upcase\n\n# good\nclass User\n  def zip\n    address&.zip\n  end\nend\nuser&.zip&.upcase\n----\n\n=== Spaces and Braces [[spaces-braces]]\n\nNo spaces after `(`, `[` or before `]`, `)`.\nUse spaces around `{` and before `}`.\n\n[source,ruby]\n----\n# bad\nsome( arg ).other\n[ 1, 2, 3 ].each{|e| puts e}\n\n# good\nsome(arg).other\n[1, 2, 3].each { |e| puts e }\n----\n\n`{` and `}` deserve a bit of clarification, since they are used for block and hash literals, as well as string interpolation.\n\nFor hash literals two styles are considered acceptable.\nThe first variant is slightly more readable (and arguably more popular in the Ruby community in general).\nThe second variant has the advantage of adding visual difference between block and hash literals.\nWhichever one you pick - apply it consistently.\n\n[source,ruby]\n----\n# good - space after { and before }\n{ one: 1, two: 2 }\n\n# good - no space after { and before }\n{one: 1, two: 2}\n----\n\nWith interpolated expressions, there should be no padded-spacing inside the braces.\n\n[source,ruby]\n----\n# bad\n\"From: #{ user.first_name }, #{ user.last_name }\"\n\n# good\n\"From: #{user.first_name}, #{user.last_name}\"\n----\n\n=== No Space after Bang [[no-space-bang]]\n\nNo space after `!`.\n\n[source,ruby]\n----\n# bad\n! something\n\n# good\n!something\n----\n\n=== No Space inside Range Literals [[no-space-inside-range-literals]]\n\nNo space inside range literals.\n\n[source,ruby]\n----\n# bad\n1 .. 3\n'a' ... 'z'\n\n# good\n1..3\n'a'...'z'\n----\n\n=== Indent `when` to `case` [[indent-when-to-case]]\n\nIndent `when` as deep as `case`.\n\n[source,ruby]\n----\n# bad\ncase\n  when song.name == 'Misty'\n    puts 'Not again!'\n  when song.duration > 120\n    puts 'Too long!'\n  when Time.now.hour > 21\n    puts \"It's too late\"\n  else\n    song.play\nend\n\n# good\ncase\nwhen song.name == 'Misty'\n  puts 'Not again!'\nwhen song.duration > 120\n  puts 'Too long!'\nwhen Time.now.hour > 21\n  puts \"It's too late\"\nelse\n  song.play\nend\n----\n\n.A Bit of History\n****\nThis is the style established in both \"The Ruby Programming Language\" and \"Programming Ruby\".\nHistorically it is derived from the fact that `case` and `switch` statements are not blocks, hence should not be indented, and the `when` and `else` keywords are labels (compiled in the C language, they are literally labels for `JMP` calls).\n****\n\n=== Indent Conditional Assignment [[indent-conditional-assignment]]\n\nWhen assigning the result of a conditional expression to a variable, preserve the usual alignment of its branches.\n\n[source,ruby]\n----\n# bad - pretty convoluted\nkind = case year\nwhen 1850..1889 then 'Blues'\nwhen 1890..1909 then 'Ragtime'\nwhen 1910..1929 then 'New Orleans Jazz'\nwhen 1930..1939 then 'Swing'\nwhen 1940..1950 then 'Bebop'\nelse 'Jazz'\nend\n\nresult = if some_cond\n  calc_something\nelse\n  calc_something_else\nend\n\n# good - it's apparent what's going on\nkind = case year\n       when 1850..1889 then 'Blues'\n       when 1890..1909 then 'Ragtime'\n       when 1910..1929 then 'New Orleans Jazz'\n       when 1930..1939 then 'Swing'\n       when 1940..1950 then 'Bebop'\n       else 'Jazz'\n       end\n\nresult = if some_cond\n           calc_something\n         else\n           calc_something_else\n         end\n\n# good (and a bit more width efficient)\nkind =\n  case year\n  when 1850..1889 then 'Blues'\n  when 1890..1909 then 'Ragtime'\n  when 1910..1929 then 'New Orleans Jazz'\n  when 1930..1939 then 'Swing'\n  when 1940..1950 then 'Bebop'\n  else 'Jazz'\n  end\n\nresult =\n  if some_cond\n    calc_something\n  else\n    calc_something_else\n  end\n----\n\n=== Empty Lines between Methods [[empty-lines-between-methods]]\n\nUse empty lines between method definitions and also to break up methods into logical paragraphs internally.\n\n[source,ruby]\n----\n# bad\ndef some_method\n  data = initialize(options)\n  data.manipulate!\n  data.result\nend\ndef some_other_method\n  result\nend\n\n# good\ndef some_method\n  data = initialize(options)\n\n  data.manipulate!\n\n  data.result\nend\n\ndef some_other_method\n  result\nend\n----\n\n=== Two or More Empty Lines [[two-or-more-empty-lines]]\n\nDon't use several empty lines in a row.\n\n[source,ruby]\n----\n# bad - It has two empty lines.\nsome_method\n\n\nsome_method\n\n# good\nsome_method\n\nsome_method\n----\n\n=== Empty Lines after Module Inclusion [[empty-lines-after-module-inclusion]]\n\nUse empty lines after module inclusion methods (`extend`, `include` and `prepend`).\n\n[source,ruby]\n----\n# bad\nclass Foo\n  extend SomeModule\n  include AnotherModule\n  prepend YetAnotherModule\n  def foo; end\nend\n\n# good\nclass Foo\n  extend SomeModule\n  include AnotherModule\n  prepend YetAnotherModule\n\n  def foo; end\nend\n----\n\n=== Empty Lines around Attribute Accessor [[empty-lines-around-attribute-accessor]]\n\nUse empty lines around attribute accessor.\n\n[source,ruby]\n----\n# bad\nclass Foo\n  attr_reader :foo\n  def foo\n    # do something...\n  end\nend\n\n# good\nclass Foo\n  attr_reader :foo\n\n  def foo\n    # do something...\n  end\nend\n----\n\n=== Empty Lines around Access Modifier [[empty-lines-around-access-modifier]]\n\nUse empty lines around access modifier.\n\n[source,ruby]\n----\n# bad\nclass Foo\n  def bar; end\n  private\n  def baz; end\nend\n\n# good\nclass Foo\n  def bar; end\n\n  private\n\n  def baz; end\nend\n----\n\n=== Empty Lines around Bodies [[empty-lines-around-bodies]]\n\nDon't use empty lines around method, class, module, block bodies.\n\n[source,ruby]\n----\n# bad\nclass Foo\n\n  def foo\n\n    begin\n\n      do_something do\n\n        something\n\n      end\n\n    rescue\n\n      something\n\n    end\n\n    true\n\n  end\n\nend\n\n# good\nclass Foo\n  def foo\n    begin\n      do_something do\n        something\n      end\n    rescue\n      something\n    end\n  end\nend\n----\n\n=== Trailing Comma in Method Arguments [[no-trailing-params-comma]]\n\nAvoid comma after the last parameter in a method call, especially when the parameters are not on separate lines.\n\n[source,ruby]\n----\n# bad - easier to move/add/remove parameters, but still not preferred\nsome_method(\n  size,\n  count,\n  color,\n)\n\n# bad\nsome_method(size, count, color, )\n\n# good\nsome_method(size, count, color)\n----\n\n=== Spaces around Equals [[spaces-around-equals]]\n\nUse spaces around the `=` operator when assigning default values to method parameters:\n\n[source,ruby]\n----\n# bad\ndef some_method(arg1=:default, arg2=nil, arg3=[])\n  # do something...\nend\n\n# good\ndef some_method(arg1 = :default, arg2 = nil, arg3 = [])\n  # do something...\nend\n----\n\nWhile several Ruby books suggest the first style, the second is much more\nprominent in practice (and arguably a bit more readable).\n\n=== Line Continuation in Expressions [[no-trailing-backslash]]\n\nAvoid line continuation with `\\` where not required.\nIn practice, avoid using line continuations for anything but string concatenation.\n\n[source,ruby]\n----\n# bad (\\ is not needed here)\nresult = 1 - \\\n         2\n\n# bad (\\ is required, but still ugly as hell)\nresult = 1 \\\n         - 2\n\n# good\nresult = 1 -\n         2\n\nlong_string = 'First part of the long string' \\\n              ' and second part of the long string'\n----\n\n=== Multi-line Method Chains [[consistent-multi-line-chains]]\n\nAdopt a consistent multi-line method chaining style.\nThere are two popular styles in the Ruby community, both of which are considered good - leading `.`  and trailing `.`.\n\n==== Leading `.` [[leading-dot-in-multi-line-chains]]\n\nWhen continuing a chained method call on another line, keep the `.` on the second line.\n\n[source,ruby]\n----\n# bad - need to consult first line to understand second line\none.two.three.\n  four\n\n# good - it's immediately clear what's going on the second line\none.two.three\n  .four\n----\n\n==== Trailing `.` [[trailing-dot-in-multi-line-chains]]\n\nWhen continuing a chained method call on another line, include the `.` on the first line to indicate that the expression continues.\n\n[source,ruby]\n----\n# bad - need to read ahead to the second line to know that the chain continues\none.two.three\n  .four\n\n# good - it's immediately clear that the expression continues beyond the first line\none.two.three.\n  four\n----\n\nA discussion on the merits of both alternative styles can be found https://github.com/rubocop/ruby-style-guide/pull/176[here].\n\n=== Method Arguments Alignment [[no-double-indent]]\n\nAlign the arguments of a method call if they span more than one line.\nWhen aligning arguments is not appropriate due to line-length constraints, single indent for the lines after the first is also acceptable.\n\n[source,ruby]\n----\n# starting point (line is too long)\ndef send_mail(source)\n  Mailer.deliver(to: 'bob@example.com', from: 'us@example.com', subject: 'Important message', body: source.text)\nend\n\n# bad (double indent)\ndef send_mail(source)\n  Mailer.deliver(\n      to: 'bob@example.com',\n      from: 'us@example.com',\n      subject: 'Important message',\n      body: source.text)\nend\n\n# good\ndef send_mail(source)\n  Mailer.deliver(to: 'bob@example.com',\n                 from: 'us@example.com',\n                 subject: 'Important message',\n                 body: source.text)\nend\n\n# good (normal indent)\ndef send_mail(source)\n  Mailer.deliver(\n    to: 'bob@example.com',\n    from: 'us@example.com',\n    subject: 'Important message',\n    body: source.text\n  )\nend\n----\n\n=== Implicit Options Hash [[no-braces-opts-hash]]\n\nIMPORTANT: As of Ruby 2.7 braces around an options hash are no longer\noptional.\n\nOmit the outer braces around an implicit options hash.\n\n[source,ruby]\n----\n# bad\nuser.set({ name: 'John', age: 45, permissions: { read: true } })\n\n# good\nuser.set(name: 'John', age: 45, permissions: { read: true })\n----\n\n=== DSL Method Calls [[no-dsl-decorating]]\n\nOmit both the outer braces and parentheses for methods that are part of an internal DSL (e.g., Rake, Rails, RSpec).\n\n[source,ruby]\n----\nclass Person < ActiveRecord::Base\n  # bad\n  attr_reader(:name, :age)\n  # good\n  attr_reader :name, :age\n\n  # bad\n  validates(:name, { presence: true, length: { within: 1..10 } })\n  # good\n  validates :name, presence: true, length: { within: 1..10 }\nend\n----\n\n=== Space in Method Calls [[parens-no-spaces]]\n\nDo not put a space between a method name and the opening parenthesis.\n\n[source,ruby]\n----\n# bad\nputs (x + y)\n\n# good\nputs(x + y)\n----\n\n=== Space in Brackets Access\n\nDo not put a space between a receiver name and the opening brackets.\n\n[source,ruby]\n----\n# bad\ncollection [index_or_key]\n\n# good\ncollection[index_or_key]\n----\n\n=== Multi-line Arrays Alignment [[align-multiline-arrays]]\n\nAlign the elements of array literals spanning multiple lines.\n\n[source,ruby]\n----\n# bad - single indent\nmenu_item = %w[Spam Spam Spam Spam Spam Spam Spam Spam\n  Baked beans Spam Spam Spam Spam Spam]\n\n# good\nmenu_item = %w[\n  Spam Spam Spam Spam Spam Spam Spam Spam\n  Baked beans Spam Spam Spam Spam Spam\n]\n\n# good\nmenu_item =\n  %w[Spam Spam Spam Spam Spam Spam Spam Spam\n     Baked beans Spam Spam Spam Spam Spam]\n----\n\n== Naming Conventions\n\n[quote, Phil Karlton]\n____\nThe only real difficulties in programming are cache invalidation and naming things.\n____\n\n=== English for Identifiers [[english-identifiers]]\n\nName identifiers in English.\n\n[source,ruby]\n----\n# bad - identifier is a Bulgarian word, using non-ascii (Cyrillic) characters\nзаплата = 1_000\n\n# bad - identifier is a Bulgarian word, written with Latin letters (instead of Cyrillic)\nzaplata = 1_000\n\n# good\nsalary = 1_000\n----\n\n=== Snake Case for Symbols, Methods and Variables [[snake-case-symbols-methods-vars]]\n\nUse `snake_case` for symbols, methods and variables.\n\n[source,ruby]\n----\n# bad\n:'some symbol'\n:SomeSymbol\n:someSymbol\n\nsomeVar = 5\n\ndef someMethod\n  # some code\nend\n\ndef SomeMethod\n  # some code\nend\n\n# good\n:some_symbol\n\nsome_var = 5\n\ndef some_method\n  # some code\nend\n----\n\n=== Identifiers with a Numeric Suffix [[snake-case-symbols-methods-vars-with-numbers]]\n\nDo not separate numbers from letters on symbols, methods and variables.\n\n[source,ruby]\n----\n# bad\n:some_sym_1\n\nsome_var_1 = 1\n\nvar_10 = 10\n\ndef some_method_1\n  # some code\nend\n\n# good\n:some_sym1\n\nsome_var1 = 1\n\nvar10 = 10\n\ndef some_method1\n  # some code\nend\n----\n\n=== CapitalCase for Classes and Modules [[camelcase-classes]]\n\nNOTE: `CapitalCase` is also known as `UpperCamelCase`, `CapitalWords`\nand `PascalCase`.\n\nUse `CapitalCase` for classes and modules.\n(Keep acronyms like HTTP, RFC, XML uppercase).\n\n[source,ruby]\n----\n# bad\nclass Someclass\n  # some code\nend\n\nclass Some_Class\n  # some code\nend\n\nclass SomeXml\n  # some code\nend\n\nclass XmlSomething\n  # some code\nend\n\n# good\nclass SomeClass\n  # some code\nend\n\nclass SomeXML\n  # some code\nend\n\nclass XMLSomething\n  # some code\nend\n----\n\n=== Snake Case for Files [[snake-case-files]]\n\nUse `snake_case` for naming files, e.g. `hello_world.rb`.\n\n=== Snake Case for Directories [[snake-case-dirs]]\n\nUse `snake_case` for naming directories, e.g. `lib/hello_world/hello_world.rb`.\n\n=== One Class per File [[one-class-per-file]]\n\nAim to have just a single class/module per source file.\nName the file name as the class/module, but replacing `CapitalCase` with `snake_case`.\n\n=== Screaming Snake Case for Constants [[screaming-snake-case]]\n\nUse `SCREAMING_SNAKE_CASE` for other constants (those that don't refer to classes and modules).\n\n[source,ruby]\n----\n# bad\nSomeConst = 5\n\n# good\nSOME_CONST = 5\n----\n\n=== Predicate Methods Suffix [[bool-methods-qmark]]\n\nThe names of predicate methods (methods that return a boolean value) should end in a question mark  (i.e. `Array#empty?`).\nMethods that don't return a boolean, shouldn't end in a question mark.\n\n[source,ruby]\n----\n# bad\ndef even(value)\nend\n\n# good\ndef even?(value)\nend\n----\n\n=== Predicate Methods Prefix [[bool-methods-prefix]]\n\nAvoid prefixing predicate methods with the auxiliary verbs such as `is`, `does`, or `can`.\nThese words are redundant and inconsistent with the style of boolean methods in the Ruby core library, such as `empty?` and `include?`.\n\n[source,ruby]\n----\n# bad\nclass Person\n  def is_tall?\n    true\n  end\n\n  def can_play_basketball?\n    false\n  end\n\n  def does_like_candy?\n    true\n  end\nend\n\n# good\nclass Person\n  def tall?\n    true\n  end\n\n  def basketball_player?\n    false\n  end\n\n  def likes_candy?\n    true\n  end\nend\n----\n\n=== Dangerous Method Suffix [[dangerous-method-bang]]\n\nThe names of potentially _dangerous_ methods (i.e. methods that modify `self` or the arguments, `exit!` (doesn't run the finalizers like `exit` does), etc) should end with an exclamation mark if there exists a safe version of that _dangerous_ method.\n\n[source,ruby]\n----\n# bad - there is no matching 'safe' method\nclass Person\n  def update!\n  end\nend\n\n# good\nclass Person\n  def update\n  end\nend\n\n# good\nclass Person\n  def update!\n  end\n\n  def update\n  end\nend\n----\n\n=== Relationship between Safe and Dangerous Methods [[safe-because-unsafe]]\n\nDefine the non-bang (safe) method in terms of the bang (dangerous) one if possible.\n\n[source,ruby]\n----\nclass Array\n  def flatten_once!\n    res = []\n\n    each do |e|\n      [*e].each { |f| res << f }\n    end\n\n    replace(res)\n  end\n\n  def flatten_once\n    dup.flatten_once!\n  end\nend\n----\n\n=== Unused Variables Prefix [[underscore-unused-vars]]\n\nPrefix with `+_+` unused block parameters and local variables.\nIt's also acceptable to use just `+_+` (although it's a bit less descriptive).\nThis convention is recognized by the Ruby interpreter and tools like RuboCop will suppress their unused variable warnings.\n\n[source,ruby]\n----\n# bad\nresult = hash.map { |k, v| v + 1 }\n\ndef something(x)\n  unused_var, used_var = something_else(x)\n  # some code\nend\n\n# good\nresult = hash.map { |_k, v| v + 1 }\n\ndef something(x)\n  _unused_var, used_var = something_else(x)\n  # some code\nend\n\n# good\nresult = hash.map { |_, v| v + 1 }\n\ndef something(x)\n  _, used_var = something_else(x)\n  # some code\nend\n----\n\n=== `other` Parameter [[other-arg]]\n\nWhen defining binary operators and operator-alike methods, name the parameter `other` for operators with \"symmetrical\" semantics of operands.\nSymmetrical semantics means both sides of the operator are typically of the same or coercible types.\n\nOperators and operator-alike methods with symmetrical semantics (the parameter should be named `other`): `+`, `-`, `+*+`, `/`, `%`, `**`, `==`, `>`, `<`, `|`, `&`, `^`, `eql?`, `equal?`.\n\nOperators with non-symmetrical semantics (the parameter should *not* be named `other`): `<<`, `[]` (collection/item relations between operands), `===` (pattern/matchable relations).\n\nNote that the rule should be followed *only* if both sides of the operator have the same semantics.\nProminent exception in Ruby core is, for example, `Array#*(int)`.\n\n[source,ruby]\n----\n# good\ndef +(other)\n  # body omitted\nend\n\n# bad\ndef <<(other)\n  @internal << other\nend\n\n# good\ndef <<(item)\n  @internal << item\nend\n\n# bad\n# Returns some string multiplied `other` times\ndef *(other)\n  # body omitted\nend\n\n# good\n# Returns some string multiplied `num` times\ndef *(num)\n  # body omitted\nend\n----\n\n== Flow of Control\n\n=== `for` Loops [[no-for-loops]]\n\nDo not use `for`, unless you know exactly why.\nMost of the time iterators should be used instead.\n`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.\n\n[source,ruby]\n----\narr = [1, 2, 3]\n\n# bad\nfor elem in arr do\n  puts elem\nend\n\n# note that elem is accessible outside of the for loop\nelem # => 3\n\n# good\narr.each { |elem| puts elem }\n\n# elem is not accessible outside each block\nelem # => NameError: undefined local variable or method `elem'\n----\n\n=== `then` in Multi-line Expression [[no-then]]\n\nDo not use `then` for multi-line `if`/`unless`/`when`/`in`.\n\n[source,ruby]\n----\n# bad\nif some_condition then\n  # body omitted\nend\n\n# bad\ncase foo\nwhen bar then\n  # body omitted\nend\n\n# bad\ncase expression\nin pattern then\n  # body omitted\nend\n\n# good\nif some_condition\n  # body omitted\nend\n\n# good\ncase foo\nwhen bar\n  # body omitted\nend\n\n# good\ncase expression\nin pattern\n  # body omitted\nend\n----\n\n=== Condition Placement [[same-line-condition]]\n\nAlways put the condition on the same line as the `if`/`unless` in a multi-line conditional.\n\n[source,ruby]\n----\n# bad\nif\n  some_condition\n  do_something\n  do_something_else\nend\n\n# good\nif some_condition\n  do_something\n  do_something_else\nend\n----\n\n=== Ternary Operator vs `if` [[ternary-operator]]\n\nPrefer the ternary operator(`?:`) over `if/then/else/end` constructs.\nIt's more common and obviously more concise.\n\n[source,ruby]\n----\n# bad\nresult = if some_condition then something else something_else end\n\n# good\nresult = some_condition ? something : something_else\n----\n\n=== Nested Ternary Operators [[no-nested-ternary]]\n\nUse one expression per branch in a ternary operator.\nThis also means that ternary operators must not be nested.\nPrefer `if/else` constructs in these cases.\n\n[source,ruby]\n----\n# bad\nsome_condition ? (nested_condition ? nested_something : nested_something_else) : something_else\n\n# good\nif some_condition\n  nested_condition ? nested_something : nested_something_else\nelse\n  something_else\nend\n----\n\n=== Semicolon in `if` [[no-semicolon-ifs]]\n\nDo not use `if x; ...`. Use the ternary operator instead.\n\n[source,ruby]\n----\n# bad\nresult = if some_condition; something else something_else end\n\n# good\nresult = some_condition ? something : something_else\n----\n\n=== `case` vs `if-else` [[case-vs-if-else]]\n\nPrefer `case` over `if-elsif` when compared value is the same in each clause.\n\n[source,ruby]\n----\n# bad\nif status == :active\n  perform_action\nelsif status == :inactive || status == :hibernating\n  check_timeout\nelse\n  final_action\nend\n\n# good\ncase status\nwhen :active\n  perform_action\nwhen :inactive, :hibernating\n  check_timeout\nelse\n  final_action\nend\n----\n\n=== Returning Result from `if`/`case` [[use-if-case-returns]]\n\nLeverage the fact that `if` and `case` are expressions which return a result.\n\n[source,ruby]\n----\n# bad\nif condition\n  result = x\nelse\n  result = y\nend\n\n# good\nresult =\n  if condition\n    x\n  else\n    y\n  end\n----\n\n=== One-line Cases [[one-line-cases]]\n\nUse `when x then ...` for one-line cases.\n\n[source,ruby]\n----\n# bad\ncase year\nwhen 1850..1889\n  'Blues'\nwhen 1890..1909\n  'Ragtime'\nwhen 1910..1929\n  'New Orleans Jazz'\nwhen 1930..1939\n  'Swing'\nwhen 1940..1950\n  'Bebop'\nelse\n  'Jazz'\nend\n\n# good\ncase year\nwhen 1850..1889 then 'Blues'\nwhen 1890..1909 then 'Ragtime'\nwhen 1910..1929 then 'New Orleans Jazz'\nwhen 1930..1939 then 'Swing'\nwhen 1940..1950 then 'Bebop'\nelse                  'Jazz'\nend\n----\n\nNOTE: The alternative syntax `when x: ...` has been removed as of Ruby 1.9.\n\n=== Semicolon in `when` [[no-when-semicolons]]\n\nDo not use `when x; ...`. See the previous rule.\n\n[source,ruby]\n----\n# bad\ncase year\nwhen 1850..1889; 'Blues'\nwhen 1890..1909; 'Ragtime'\nelse; 'Jazz'\nend\n\n# good\ncase year\nwhen 1850..1889 then 'Blues'\nwhen 1890..1909 then 'Ragtime'\nelse                  'Jazz'\nend\n----\n\n=== Semicolon in `in` [[no-in-pattern-semicolons]]\n\nDo not use `in pattern; ...`. Use `in pattern then ...` for one-line `in` pattern branches.\n\n[source,ruby]\n----\n# bad\ncase expression\nin pattern; do_something\nend\n\n# good\ncase expression\nin pattern then do_something\nend\n----\n\n=== `!` vs `not` [[bang-not-not]]\n\nUse `!` instead of `not`.\n\n[source,ruby]\n----\n# bad - parentheses are required because of op precedence\nx = (not something)\n\n# good\nx = !something\n----\n\n=== Double Negation [[no-bang-bang]]\n\nAvoid unnecessary uses of `!!`\n\n`!!` converts a value to boolean, but you don't need this explicit conversion in the condition of a control expression; using it only obscures your intention.\n\nConsider using it only when there is a valid reason to restrict the result `true` or `false`. Examples include outputting to a particular format or API like JSON, or as the return value of a `predicate?` method. In these cases, also consider doing a nil check instead: `!something.nil?`.\n\n[source,ruby]\n----\n# bad\nx = 'test'\n# obscure nil check\nif !!x\n  # body omitted\nend\n\n# good\nx = 'test'\nif x\n  # body omitted\nend\n\n# good\ndef named?\n  !name.nil?\nend\n\n# good\ndef banned?\n  !!banned_until&.future?\nend\n----\n\n=== `and`/`or` [[no-and-or-or]] [[and-or-flow]]\n\nDo not use `and` and `or` in boolean context - `and` and `or` are control flow\noperators and should be used as such. They have very low precedence, and can be\nused as a short form of specifying flow sequences like \"evaluate expression 1,\nand only if it is not successful (returned `nil`), evaluate expression 2\". This\nis especially useful for raising errors or early return without breaking the\nreading flow.\n\n[source,ruby]\n----\n# good: and/or for control flow\nx = extract_arguments or raise ArgumentError, \"Not enough arguments!\"\nuser.suspended? and return :denied\n\n# bad\n# and/or in conditions (their precedence is low, might produce unexpected result)\nif got_needed_arguments and arguments_valid\n  # ...body omitted\nend\n# in logical expression calculation\nok = got_needed_arguments and arguments_valid\n\n# good\n# &&/|| in conditions\nif got_needed_arguments && arguments_valid\n  # ...body omitted\nend\n# in logical expression calculation\nok = got_needed_arguments && arguments_valid\n\n# bad\n# &&/|| for control flow (can lead to very surprising results)\nx = extract_arguments || raise(ArgumentError, \"Not enough arguments!\")\n----\n\nAvoid several control flow operators in one expression, as that quickly\nbecomes confusing:\n\n[source,ruby]\n----\n# bad\n# Did author mean conditional return because `#log` could result in `nil`?\n# ...or was it just to have a smart one-liner?\nx = extract_arguments and log(\"extracted\") and return\n\n# good\n# If the intention was conditional return\nx = extract_arguments\nif x\n  return if log(\"extracted\")\nend\n# If the intention was just \"log, then return\"\nx = extract_arguments\nif x\n  log(\"extracted\")\n  return\nend\n----\n\nNOTE: Whether organizing control flow with `and` and `or` is a good idea has been a controversial topic in the community for a long time. But if you do, prefer these operators over `&&`/`||`. As the different operators are meant to have different semantics that makes it easier to reason whether you're dealing with a logical expression (that will get reduced to a boolean value) or with flow of control.\n\n.Why is using `and` and `or` as logical operators a bad idea?\n****\nSimply put - because they add some cognitive overhead, as they don't behave like similarly named logical operators in other languages.\n\nFirst of all, `and` and `or` operators have lower precedence than the `=` operator, whereas the `&&` and `||` operators have higher precedence than the `=` operator, based on order of operations.\n\n[source,ruby]\n----\nfoo = true and false # results in foo being equal to true. Equivalent to (foo = true) and false\nbar = false or true  # results in bar being equal to false. Equivalent to (bar = false) or true\n----\n\nAlso `&&` has higher precedence than `||`, whereas `and` and `or` have the same one. Funny enough, even though `and` and `or`\nwere inspired by Perl, they don't have different precedence in Perl.\n\n[source,ruby]\n----\ntrue or true and false # => false (it's effectively (true or true) and false)\ntrue || true && false # => true (it's effectively true || (true && false)\nfalse or true and false # => false (it's effectively (false or true) and false)\nfalse || true && false # => false (it's effectively false || (true && false))\n----\n****\n\n=== Multi-line Ternary Operator [[no-multiline-ternary]]\n\nAvoid multi-line `?:` (the ternary operator); use `if`/`unless` instead.\n\n[source,ruby]\n----\n# bad\nresult = some_condition ?\n  something :\n  something_else\n\n# good\nresult =\n  if some_condition\n    something\n  else\n    something_else\n  end\n----\n\n=== `if` as a Modifier [[if-as-a-modifier]]\n\nPrefer modifier `if`/`unless` usage when you have a single-line body.\nAnother good alternative is the usage of control flow `and`/`or`.\n\n[source,ruby]\n----\n# bad\nif some_condition\n  do_something\nend\n\n# good\ndo_something if some_condition\n\n# another good option\nsome_condition and do_something\n----\n\n=== Multi-line `if` Modifiers [[no-multiline-if-modifiers]]\n\nAvoid modifier `if`/`unless` usage at the end of a non-trivial multi-line block.\n\n[source,ruby]\n----\n# bad\n10.times do\n  # multi-line body omitted\nend if some_condition\n\n# good\nif some_condition\n  10.times do\n    # multi-line body omitted\n  end\nend\n----\n\n=== Nested Modifiers [[no-nested-modifiers]]\n\nAvoid nested modifier `if`/`unless`/`while`/`until` usage.\nPrefer `&&`/`||` if appropriate.\n\n[source,ruby]\n----\n# bad\ndo_something if other_condition if some_condition\n\n# good\ndo_something if some_condition && other_condition\n----\n\n=== `if` vs `unless` [[unless-for-negatives]]\n\nPrefer `unless` over `if` for negative conditions (or control flow `||`).\n\n[source,ruby]\n----\n# bad\ndo_something if !some_condition\n\n# bad\ndo_something if not some_condition\n\n# good\ndo_something unless some_condition\n\n# another good option\nsome_condition || do_something\n----\n\n=== Using `else` with `unless` [[no-else-with-unless]]\n\nDo not use `unless` with `else`.\nRewrite these with the positive case first.\n\n[source,ruby]\n----\n# bad\nunless success?\n  puts 'failure'\nelse\n  puts 'success'\nend\n\n# good\nif success?\n  puts 'success'\nelse\n  puts 'failure'\nend\n----\n\n=== Parentheses around Condition [[no-parens-around-condition]]\n\nDon't use parentheses around the condition of a control expression.\n\n[source,ruby]\n----\n# bad\nif (x > 10)\n  # body omitted\nend\n\n# good\nif x > 10\n  # body omitted\nend\n----\n\nNOTE: There is an exception to this rule, namely <<safe-assignment-in-condition,safe assignment in condition>>.\n\n=== Multi-line `while do` [[no-multiline-while-do]]\n\nDo not use `while/until condition do` for multi-line `while/until`.\n\n[source,ruby]\n----\n# bad\nwhile x > 5 do\n  # body omitted\nend\n\nuntil x > 5 do\n  # body omitted\nend\n\n# good\nwhile x > 5\n  # body omitted\nend\n\nuntil x > 5\n  # body omitted\nend\n----\n\n=== `while` as a Modifier [[while-as-a-modifier]]\n\nPrefer modifier `while/until` usage when you have a single-line body.\n\n[source,ruby]\n----\n# bad\nwhile some_condition\n  do_something\nend\n\n# good\ndo_something while some_condition\n----\n\n=== `while` vs `until` [[until-for-negatives]]\n\nPrefer `until` over `while` for negative conditions.\n\n[source,ruby]\n----\n# bad\ndo_something while !some_condition\n\n# good\ndo_something until some_condition\n----\n\n=== Infinite Loop [[infinite-loop]]\n\nUse `Kernel#loop` instead of `while`/`until` when you need an infinite loop.\n\n[source,ruby]\n----\n# bad\nwhile true\n  do_something\nend\n\nuntil false\n  do_something\nend\n\n# good\nloop do\n  do_something\nend\n----\n\n=== `loop` with `break` [[loop-with-break]]\n\nUse `Kernel#loop` with `break` rather than `begin/end/until` or `begin/end/while` for post-loop tests.\n\n[source,ruby]\n----\n# bad\nbegin\n  puts val\n  val += 1\nend while val < 0\n\n# good\nloop do\n  puts val\n  val += 1\n  break unless val < 0\nend\n----\n\n=== Explicit `return` [[no-explicit-return]]\n\nAvoid `return` where not required for flow of control.\n\n[source,ruby]\n----\n# bad\ndef some_method(some_arr)\n  return some_arr.size\nend\n\n# good\ndef some_method(some_arr)\n  some_arr.size\nend\n----\n\n=== Explicit `self` [[no-self-unless-required]]\n\nAvoid `self` where not required.\n(It is only required when calling a `self` write accessor, methods named after reserved words, or overloadable operators.)\n\n[source,ruby]\n----\n# bad\ndef ready?\n  if self.last_reviewed_at > self.last_updated_at\n    self.worker.update(self.content, self.options)\n    self.status = :in_progress\n  end\n  self.status == :verified\nend\n\n# good\ndef ready?\n  if last_reviewed_at > last_updated_at\n    worker.update(content, options)\n    self.status = :in_progress\n  end\n  status == :verified\nend\n----\n\n=== Shadowing Methods [[no-shadowing]]\n\nAs a corollary, avoid shadowing methods with local variables unless they are both equivalent.\n\n[source,ruby]\n----\nclass Foo\n  attr_accessor :options\n\n  # ok\n  def initialize(options)\n    self.options = options\n    # both options and self.options are equivalent here\n  end\n\n  # bad\n  def do_something(options = {})\n    unless options[:when] == :later\n      output(self.options[:message])\n    end\n  end\n\n  # good\n  def do_something(params = {})\n    unless params[:when] == :later\n      output(options[:message])\n    end\n  end\nend\n----\n\n=== Safe Assignment in Condition [[safe-assignment-in-condition]]\n\nDon't use the return value of `=` (an assignment) in conditional expressions unless the assignment is wrapped in parentheses.\nThis is a fairly popular idiom among Rubyists that's sometimes referred to as _safe assignment in condition_.\n\n[source,ruby]\n----\n# bad (+ a warning)\nif v = array.grep(/foo/)\n  do_something(v)\n  # some code\nend\n\n# good (MRI would still complain, but RuboCop won't)\nif (v = array.grep(/foo/))\n  do_something(v)\n  # some code\nend\n\n# good\nv = array.grep(/foo/)\nif v\n  do_something(v)\n  # some code\nend\n----\n\n=== `BEGIN` Blocks [[no-BEGIN-blocks]]\n\nAvoid the use of `BEGIN` blocks.\n\n[source,ruby]\n----\n# bad\nputs 'Hello!'\nBEGIN { puts 'Initializing...' }\n\n# good\nputs 'Initializing...'\nputs 'Hello!'\n----\n\n=== `END` Blocks [[no-END-blocks]]\n\nDo not use `END` blocks. Use `Kernel#at_exit` instead.\n\n[source,ruby]\n----\n# bad\nEND { puts 'Goodbye!' }\n\n# good\nat_exit { puts 'Goodbye!' }\n----\n\n=== Nested Conditionals [[no-nested-conditionals]]\n\nAvoid use of nested conditionals for flow of control.\n\nPrefer a guard clause when you can assert invalid data.\nA guard clause is a conditional statement at the top of a function that bails out as soon as it can.\n\n[source,ruby]\n----\n# bad\ndef compute_thing(thing)\n  if thing[:foo]\n    update_with_bar(thing[:foo])\n    if thing[:foo][:bar]\n      partial_compute(thing)\n    else\n      re_compute(thing)\n    end\n  end\nend\n\n# good\ndef compute_thing(thing)\n  return unless thing[:foo]\n  update_with_bar(thing[:foo])\n  return re_compute(thing) unless thing[:foo][:bar]\n  partial_compute(thing)\nend\n----\n\nPrefer `next` in loops instead of conditional blocks.\n\n[source,ruby]\n----\n# bad\n[0, 1, 2, 3].each do |item|\n  if item > 1\n    puts item\n  end\nend\n\n# good\n[0, 1, 2, 3].each do |item|\n  next unless item > 1\n  puts item\nend\n----\n\n== Exceptions\n\n=== `raise` vs `fail` [[prefer-raise-over-fail]]\n\nPrefer `raise` over `fail` for exceptions.\n\n[source,ruby]\n----\n# bad\nfail SomeException, 'message'\n\n# good\nraise SomeException, 'message'\n----\n\n=== Raising Explicit `RuntimeError` [[no-explicit-runtimeerror]]\n\nDon't specify `RuntimeError` explicitly in the two argument version of `raise`.\n\n[source,ruby]\n----\n# bad\nraise RuntimeError, 'message'\n\n# good - signals a RuntimeError by default\nraise 'message'\n----\n\n=== Exception Class Messages [[exception-class-messages]]\n\nPrefer supplying an exception class and a message as two separate arguments to `raise`, instead of an exception instance.\n\n[source,ruby]\n----\n# bad\nraise SomeException.new('message')\n# Note that there is no way to do `raise SomeException.new('message'), backtrace`.\n\n# good\nraise SomeException, 'message'\n# Consistent with `raise SomeException, 'message', backtrace`.\n----\n\n=== `return` from `ensure` [[no-return-ensure]]\n\nDo not return from an `ensure` block.\nIf you explicitly return from a method inside an `ensure` block, the return will take precedence over any exception being raised, and the method will return as if no exception had been raised at all.\nIn effect, the exception will be silently thrown away.\n\n[source,ruby]\n----\n# bad\ndef foo\n  raise\nensure\n  return 'very bad idea'\nend\n----\n\n=== Implicit `begin` [[begin-implicit]]\n\nUse _implicit begin blocks_ where possible.\n\n[source,ruby]\n----\n# bad\ndef foo\n  begin\n    # main logic goes here\n  rescue\n    # failure handling goes here\n  end\nend\n\n# good\ndef foo\n  # main logic goes here\nrescue\n  # failure handling goes here\nend\n----\n\n=== Contingency Methods [[contingency-methods]]\n\nMitigate the proliferation of `begin` blocks by using _contingency methods_ (a term coined by Avdi Grimm).\n\n[source,ruby]\n----\n# bad\nbegin\n  something_that_might_fail\nrescue IOError\n  # handle IOError\nend\n\nbegin\n  something_else_that_might_fail\nrescue IOError\n  # handle IOError\nend\n\n# good\ndef with_io_error_handling\n  yield\nrescue IOError\n  # handle IOError\nend\n\nwith_io_error_handling { something_that_might_fail }\n\nwith_io_error_handling { something_else_that_might_fail }\n----\n\n=== Suppressing Exceptions [[dont-hide-exceptions]]\n\nDon't suppress exceptions.\n\n[source,ruby]\n----\n# bad\nbegin\n  do_something # an exception occurs here\nrescue SomeError\nend\n\n# good\nbegin\n  do_something # an exception occurs here\nrescue SomeError\n  handle_exception\nend\n\n# good\nbegin\n  do_something # an exception occurs here\nrescue SomeError\n  # Notes on why exception handling is not performed\nend\n\n# good\ndo_something rescue nil\n----\n\n=== Using `rescue` as a Modifier [[no-rescue-modifiers]]\n\nAvoid using `rescue` in its modifier form.\n\n[source,ruby]\n----\n# bad - this catches exceptions of StandardError class and its descendant classes\nread_file rescue handle_error($!)\n\n# good - this catches only the exceptions of Errno::ENOENT class and its descendant classes\ndef foo\n  read_file\nrescue Errno::ENOENT => e\n  handle_error(e)\nend\n----\n\n=== Using Exceptions for Flow of Control [[no-exceptional-flows]]\n\nDon't use exceptions for flow of control.\n\n[source,ruby]\n----\n# bad\nbegin\n  n / d\nrescue ZeroDivisionError\n  puts 'Cannot divide by 0!'\nend\n\n# good\nif d.zero?\n  puts 'Cannot divide by 0!'\nelse\n  n / d\nend\n----\n\n=== Blind Rescues [[no-blind-rescues]]\n\nAvoid rescuing the `Exception` class.\nThis will trap signals and calls to `exit`, requiring you to `kill -9` the process.\n\n[source,ruby]\n----\n# bad\nbegin\n  # calls to exit and kill signals will be caught (except kill -9)\n  exit\nrescue Exception\n  puts \"you didn't really want to exit, right?\"\n  # exception handling\nend\n\n# good\nbegin\n  # a blind rescue rescues from StandardError, not Exception as many\n  # programmers assume.\nrescue => e\n  # exception handling\nend\n\n# also good\nbegin\n  # an exception occurs here\nrescue StandardError => e\n  # exception handling\nend\n----\n\n=== Exception Rescuing Ordering [[exception-ordering]]\n\nPut more specific exceptions higher up the rescue chain, otherwise they'll never be rescued from.\n\n[source,ruby]\n----\n# bad\nbegin\n  # some code\nrescue StandardError => e\n  # some handling\nrescue IOError => e\n  # some handling that will never be executed\nend\n\n# good\nbegin\n  # some code\nrescue IOError => e\n  # some handling\nrescue StandardError => e\n  # some handling\nend\n----\n\n=== Standard Exceptions [[standard-exceptions]]\n\nPrefer the use of exceptions from the standard library over introducing new exception classes.\n\n== Files\n\n=== Reading from a file [[file-read]]\n\nUse the convenience methods `File.read` or `File.binread` when only reading a file start to finish in a single operation.\n\n[source,ruby]\n----\n## text mode\n# bad (only when reading from beginning to end - modes: 'r', 'rt', 'r+', 'r+t')\nFile.open(filename).read\nFile.open(filename, &:read)\nFile.open(filename) { |f| f.read }\nFile.open(filename) do |f|\n  f.read\nend\nFile.open(filename, 'r').read\nFile.open(filename, 'r', &:read)\nFile.open(filename, 'r') { |f| f.read }\nFile.open(filename, 'r') do |f|\n  f.read\nend\n\n# good\nFile.read(filename)\n\n## binary mode\n# bad (only when reading from beginning to end - modes: 'rb', 'r+b')\nFile.open(filename, 'rb').read\nFile.open(filename, 'rb', &:read)\nFile.open(filename, 'rb') { |f| f.read }\nFile.open(filename, 'rb') do |f|\n  f.read\nend\n\n# good\nFile.binread(filename)\n----\n\n=== Writing to a file [[file-write]]\n\nUse the convenience methods `File.write` or `File.binwrite` when only opening a file to create / replace its content in a single operation.\n\n[source,ruby]\n----\n## text mode\n# bad (only truncating modes: 'w', 'wt', 'w+', 'w+t')\nFile.open(filename, 'w').write(content)\nFile.open(filename, 'w') { |f| f.write(content) }\nFile.open(filename, 'w') do |f|\n  f.write(content)\nend\n\n# good\nFile.write(filename, content)\n\n## binary mode\n# bad (only truncating modes: 'wb', 'w+b')\nFile.open(filename, 'wb').write(content)\nFile.open(filename, 'wb') { |f| f.write(content) }\nFile.open(filename, 'wb') do |f|\n  f.write(content)\nend\n\n# good\nFile.binwrite(filename, content)\n----\n\n=== Release External Resources [[release-resources]]\n\nRelease external resources obtained by your program in an `ensure` block.\n\n[source,ruby]\n----\nf = File.open('testfile')\nbegin\n  # .. process\nrescue\n  # .. handle error\nensure\n  f.close if f\nend\n----\n\n=== Auto-release External Resources [[auto-release-resources]]\n\nUse versions of resource obtaining methods that do automatic resource cleanup when possible.\n\n[source,ruby]\n----\n# bad - you need to close the file descriptor explicitly\nf = File.open('testfile')\n# some action on the file\nf.close\n\n# good - the file descriptor is closed automatically\nFile.open('testfile') do |f|\n  # some action on the file\nend\n----\n\n=== Atomic File Operations [[atomic-file-operations]]\n\nWhen doing file operations after confirming the existence check of a file, frequent parallel file operations may cause problems that are difficult to reproduce.\nTherefore, it is preferable to use atomic file operations.\n\n[source,ruby]\n----\n# bad - race condition with another process may result in an error in `mkdir`\nunless Dir.exist?(path)\n  FileUtils.mkdir(path)\nend\n\n# good - atomic and idempotent creation\nFileUtils.mkdir_p(path)\n\n# bad - race condition with another process may result in an error in `remove`\nif File.exist?(path)\n  FileUtils.remove(path)\nend\n\n# good - atomic and idempotent removal\nFileUtils.rm_f(path)\n----\n\n=== Null Devices [[null-devices]]\n\nUse the platform independent null device (`File::NULL`) rather than hardcoding a value (`/dev/null` on Unix-like OSes, `NUL` or `NUL:` on Windows).\n\n[source,ruby]\n----\n# bad - hardcoded devices are platform specific\nFile.open(\"/dev/null\", 'w') { ... }\n\n# bad - unnecessary ternary can be replaced with `File::NULL`\nFile.open(Gem.win_platform? ? 'NUL' : '/dev/null', 'w') { ... }\n\n# good - platform independent\nFile.open(File::NULL, 'w') { ... }\n----\n\n== Assignment & Comparison\n\n=== Parallel Assignment [[parallel-assignment]]\n\nAvoid the use of parallel assignment for defining variables.\nParallel assignment is allowed when it is the return of a method call (e.g. `Hash#values_at`), used with the splat operator, or when used to swap variable assignment.\nParallel assignment is less readable than separate assignment.\n\n[source,ruby]\n----\n# bad\na, b, c, d = 'foo', 'bar', 'baz', 'foobar'\n\n# good\na = 'foo'\nb = 'bar'\nc = 'baz'\nd = 'foobar'\n\n# good - swapping variable assignment\n# Swapping variable assignment is a special case because it will allow you to\n# swap the values that are assigned to each variable.\na = 'foo'\nb = 'bar'\n\na, b = b, a\nputs a # => 'bar'\nputs b # => 'foo'\n\n# good - method return\ndef multi_return\n  [1, 2]\nend\n\nfirst, second = multi_return\n\n# good - use with splat\nfirst, *list = [1, 2, 3, 4] # first => 1, list => [2, 3, 4]\n\nhello_array = *'Hello' # => [\"Hello\"]\n\na = *(1..3) # => [1, 2, 3]\n----\n\n=== Values Swapping [[values-swapping]]\n\nUse parallel assignment when swapping 2 values.\n\n[source,ruby]\n----\n# bad\ntmp = x\nx = y\ny = tmp\n\n# good\nx, y = y, x\n----\n\n=== Dealing with Trailing Underscore Variables in Destructuring Assignment [[trailing-underscore-variables]]\n\nAvoid the use of unnecessary trailing underscore variables during\nparallel assignment. Named underscore variables are to be preferred over\nunderscore variables because of the context that they provide.\nTrailing underscore variables are necessary when there is a splat variable\ndefined on the left side of the assignment, and the splat variable is\nnot an underscore.\n\n[source,ruby]\n----\n# bad\nfoo = 'one,two,three,four,five'\n# Unnecessary assignment that does not provide useful information\nfirst, second, _ = foo.split(',')\nfirst, _, _ = foo.split(',')\nfirst, *_ = foo.split(',')\n\n# good\nfoo = 'one,two,three,four,five'\n# The underscores are needed to show that you want all elements\n# except for the last number of underscore elements\n*beginning, _ = foo.split(',')\n*beginning, something, _ = foo.split(',')\n\na, = foo.split(',')\na, b, = foo.split(',')\n# Unnecessary assignment to an unused variable, but the assignment\n# provides us with useful information.\nfirst, _second = foo.split(',')\nfirst, _second, = foo.split(',')\nfirst, *_ending = foo.split(',')\n----\n\n=== Self-assignment [[self-assignment]]\n\nUse shorthand self assignment operators whenever applicable.\n\n[source,ruby]\n----\n# bad\nx = x + y\nx = x * y\nx = x**y\nx = x / y\nx = x || y\nx = x && y\n\n# good\nx += y\nx *= y\nx **= y\nx /= y\nx ||= y\nx &&= y\n----\n\n=== Conditional Variable Initialization Shorthand [[double-pipe-for-uninit]]\n\nUse `||=` to initialize variables only if they're not already initialized.\n\n[source,ruby]\n----\n# bad\nname = name ? name : 'Bozhidar'\n\n# bad\nname = 'Bozhidar' unless name\n\n# good - set name to 'Bozhidar', only if it's nil or false\nname ||= 'Bozhidar'\n----\n\n[WARNING]\n====\nDon't use `||=` to initialize boolean variables.\n(Consider what would happen if the current value happened to be `false`.)\n\n[source,ruby]\n----\n# bad - would set enabled to true even if it was false\nenabled ||= true\n\n# good\nenabled = true if enabled.nil?\n----\n====\n\n=== Existence Check Shorthand [[double-amper-preprocess]]\n\nUse `&&=` to preprocess variables that may or may not exist.\nUsing `&&=` will change the value only if it exists, removing the need to check its existence with `if`.\n\n[source,ruby]\n----\n# bad\nif something\n  something = something.downcase\nend\n\n# bad\nsomething = something ? something.downcase : nil\n\n# ok\nsomething = something.downcase if something\n\n# good\nsomething = something && something.downcase\n\n# better\nsomething &&= something.downcase\n----\n\n=== Identity Comparison [[identity-comparison]]\n\nPrefer `equal?` over `==` when comparing `object_id`. `Object#equal?` is provided to compare objects for identity, and in contrast `Object#==` is provided for the purpose of doing value comparison.\n\n[source,ruby]\n----\n# bad\nfoo.object_id == bar.object_id\n\n# good\nfoo.equal?(bar)\n----\n\nSimilarly, prefer using `Hash#compare_by_identity` over using `object_id` for keys:\n\n[source,ruby]\n----\n# bad\nhash = {}\nhash[foo.object_id] = :bar\nif hash.key?(baz.object_id) # ...\n\n# good\nhash = {}.compare_by_identity\nhash[foo] = :bar\nif hash.key?(baz) # ...\n----\n\nNote that `Set` also has `Set#compare_by_identity` available.\n\n=== Explicit Use of the Case Equality Operator [[no-case-equality]]\n\nAvoid explicit use of the case equality operator `===`.\nAs its name implies it is meant to be used implicitly by `case` expressions and outside of them it yields some pretty confusing code.\n\n[source,ruby]\n----\n# bad\nArray === something\n(1..100) === 7\n/something/ === some_string\n\n# good\nsomething.is_a?(Array)\n(1..100).include?(7)\nsome_string.match?(/something/)\n----\n\nNOTE: With direct subclasses of `BasicObject`, using `is_a?` is not an option since `BasicObject` doesn't provide that method (it's defined in `Object`). In those\nrare cases it's OK to use `===`.\n\n=== `is_a?` vs `kind_of?` [[is-a-vs-kind-of]]\n\nPrefer `is_a?` over `kind_of?`. The two methods are synonyms, but `is_a?` is the more commonly used name in the wild.\n\n[source,ruby]\n----\n# bad\nsomething.kind_of?(Array)\n\n# good\nsomething.is_a?(Array)\n----\n\n=== `is_a?` vs `instance_of?` [[is-a-vs-instance-of]]\n\nPrefer `is_a?` over `instance_of?`.\n\nWhile the two methods are similar, `is_a?` will consider the whole inheritance\nchain (superclasses and included modules), which is what you normally would want\nto do. `instance_of?`, on the other hand, only returns `true` if an object is an\ninstance of that exact class you're checking for, not a subclass.\n\n[source,ruby]\n----\n# bad\nsomething.instance_of?(Array)\n\n# good\nsomething.is_a?(Array)\n----\n\n=== `instance_of?` vs class comparison [[instance-of-vs-class-comparison]]\n\nUse `Object#instance_of?` instead of class comparison for equality.\n\n[source,ruby]\n----\n# bad\nvar.class == Date\nvar.class.equal?(Date)\nvar.class.eql?(Date)\nvar.class.name == 'Date'\n\n# good\nvar.instance_of?(Date)\n----\n\n=== `==` vs `eql?` [[eql]]\n\nDo not use `eql?` when using `==` will do.\nThe stricter comparison semantics provided by `eql?` are rarely needed in practice.\n\n[source,ruby]\n----\n# bad - eql? is the same as == for strings\n'ruby'.eql? some_str\n\n# good\n'ruby' == some_str\n1.0.eql? x # eql? makes sense here if want to differentiate between Integer and Float 1\n----\n\n== Blocks, Procs & Lambdas\n\n=== Proc Application Shorthand [[single-action-blocks]]\n\nUse the Proc call shorthand when the called method is the only operation of a block.\n\n[source,ruby]\n----\n# bad\nnames.map { |name| name.upcase }\n\n# good\nnames.map(&:upcase)\n----\n\n=== Single-line Blocks Delimiters [[single-line-blocks]]\n\nPrefer `{...}` over `do...end` for single-line blocks.\nAvoid using `{...}` for multi-line blocks (multi-line chaining is always ugly).\nAlways use `do...end` for \"control flow\" and \"method definitions\" (e.g. in Rakefiles and certain DSLs).\nAvoid `do...end` when chaining.\n\n[source,ruby]\n----\nnames = %w[Bozhidar Filipp Sarah]\n\n# bad\nnames.each do |name|\n  puts name\nend\n\n# good\nnames.each { |name| puts name }\n\n# bad\nnames.select do |name|\n  name.start_with?('S')\nend.map { |name| name.upcase }\n\n# good\nnames.select { |name| name.start_with?('S') }.map(&:upcase)\n----\n\nSome will argue that multi-line chaining would look OK with the use of {...}, but they should ask themselves - is this code really readable and can the blocks' contents be extracted into nifty methods?\n\n=== Single-line `do`...`end` block [[single-line-do-end-block]]\n\nUse multi-line `do`...`end` block instead of single-line `do`...`end` block.\n\n[source,ruby]\n----\n# bad\nfoo do |arg| bar(arg) end\n\n# good\nfoo do |arg|\n  bar(arg)\nend\n\n# bad\n->(arg) do bar(arg) end\n\n# good\n->(arg) { bar(arg) }\n----\n\n=== Explicit Block Argument [[block-argument]]\n\nConsider using explicit block argument to avoid writing block literal that just passes its arguments to another block.\n\n[source,ruby]\n----\nrequire 'tempfile'\n\n# bad\ndef with_tmp_dir\n  Dir.mktmpdir do |tmp_dir|\n    Dir.chdir(tmp_dir) { |dir| yield dir }  # block just passes arguments\n  end\nend\n\n# good\ndef with_tmp_dir(&block)\n  Dir.mktmpdir do |tmp_dir|\n    Dir.chdir(tmp_dir, &block)\n  end\nend\n\nwith_tmp_dir do |dir|\n  puts \"dir is accessible as a parameter and pwd is set: #{dir}\"\nend\n----\n\n=== Trailing Comma in Block Parameters [[no-trailing-parameters-comma]]\n\nAvoid comma after the last parameter in a block, except in cases where only a single argument is present and its removal would affect functionality (for instance, array destructuring).\n\n[source,ruby]\n----\n# bad - easier to move/add/remove parameters, but still not preferred\n[[1, 2, 3], [4, 5, 6]].each do |a, b, c,|\n  a + b + c\nend\n\n# good\n[[1, 2, 3], [4, 5, 6]].each do |a, b, c|\n  a + b + c\nend\n\n# bad\n[[1, 2, 3], [4, 5, 6]].each { |a, b, c,| a + b + c }\n\n# good\n[[1, 2, 3], [4, 5, 6]].each { |a, b, c| a + b + c }\n\n# good - this comma is meaningful for array destructuring\n[[1, 2, 3], [4, 5, 6]].map { |a,| a }\n----\n\n\n=== Nested Method Definitions [[no-nested-methods]]\n\nDo not use nested method definitions, use lambda instead.\nNested method definitions actually produce methods in the same scope (e.g. class) as the outer method.\nFurthermore, the \"nested method\" will be redefined every time the method containing its definition is called.\n\n[source,ruby]\n----\n# bad\ndef foo(x)\n  def bar(y)\n    # body omitted\n  end\n\n  bar(x)\nend\n\n# good - the same as the previous, but no bar redefinition on every foo call\ndef bar(y)\n  # body omitted\nend\n\ndef foo(x)\n  bar(x)\nend\n\n# also good\ndef foo(x)\n  bar = ->(y) { ... }\n  bar.call(x)\nend\n----\n\n=== Multi-line Lambda Definition [[lambda-multi-line]]\n\nUse the new lambda literal syntax for single-line body blocks.\nUse the `lambda` method for multi-line blocks.\n\n[source,ruby]\n----\n# bad\nl = lambda { |a, b| a + b }\nl.call(1, 2)\n\n# correct, but looks extremely awkward\nl = ->(a, b) do\n  tmp = a * 7\n  tmp * b / 50\nend\n\n# good\nl = ->(a, b) { a + b }\nl.call(1, 2)\n\nl = lambda do |a, b|\n  tmp = a * 7\n  tmp * b / 50\nend\n----\n\n=== Stabby Lambda Definition with Parameters [[stabby-lambda-with-args]]\n\nDon't omit the parameter parentheses when defining a stabby lambda with parameters.\n\n[source,ruby]\n----\n# bad\nl = ->x, y { something(x, y) }\n\n# good\nl = ->(x, y) { something(x, y) }\n----\n\n=== Stabby Lambda Definition without Parameters [[stabby-lambda-no-args]]\n\nOmit the parameter parentheses when defining a stabby lambda with no parameters.\n\n[source,ruby]\n----\n# bad\nl = ->() { something }\n\n# good\nl = -> { something }\n----\n\n=== `proc` vs `Proc.new` [[proc]]\n\nPrefer `proc` over `Proc.new`.\n\n[source,ruby]\n----\n# bad\np = Proc.new { |n| puts n }\n\n# good\np = proc { |n| puts n }\n----\n\n=== Proc Call [[proc-call]]\n\nPrefer `proc.call()` over `proc[]` or `proc.()` for both lambdas and procs.\n\n[source,ruby]\n----\n# bad - looks similar to Enumeration access\nl = ->(v) { puts v }\nl[1]\n\n# bad - most compact form, but might be confusing for newcomers to Ruby\nl = ->(v) { puts v }\nl.(1)\n\n# good - a bit verbose, but crystal clear\nl = ->(v) { puts v }\nl.call(1)\n----\n\n== Methods\n\n=== Short Methods [[short-methods]]\n\nAvoid methods longer than 10 LOC (lines of code).\nIdeally, most methods will be shorter than 5 LOC.\nEmpty lines do not contribute to the relevant LOC.\n\n=== Top-Level Methods\n\nAvoid top-level method definitions. Organize them in modules, classes or structs instead.\n\nNOTE: It is fine to use top-level method definitions in scripts.\n\n[source,ruby]\n----\n# bad\ndef some_method; end\n\n# good\nclass SomeClass\n  def some_method; end\nend\n----\n\n=== No Single-line Methods [[no-single-line-methods]]\n\nAvoid single-line methods.\nAlthough they are somewhat popular in the wild, there are a few peculiarities about their definition syntax that make their use undesirable.\nAt any rate - there should be no more than one expression in a single-line method.\n\nNOTE: Ruby 3 introduced an alternative syntax for single-line method definitions, that's discussed in the next section\nof the guide.\n\n[source,ruby]\n----\n# bad\ndef too_much; something; something_else; end\n\n# okish - notice that the first ; is required\ndef no_braces_method; body end\n\n# okish - notice that the second ; is optional\ndef no_braces_method; body; end\n\n# okish - valid syntax, but no ; makes it kind of hard to read\ndef some_method() body end\n\n# good\ndef some_method\n  body\nend\n----\n\nOne exception to the rule are empty-body methods.\n\n[source,ruby]\n----\n# good\ndef no_op; end\n----\n\n=== Endless Methods\n\nOnly use Ruby 3.0's endless method definitions with a single line\nbody.  Ideally, such method definitions should be both simple (a\nsingle expression) and free of side effects.\n\nNOTE: It's important to understand that this guideline doesn't\ncontradict the previous one. We still caution against the use of\nsingle-line method definitions, but if such methods are to be used,\nprefer endless methods.\n\n[source,ruby]\n----\n# bad\ndef fib(x) = if x < 2\n  x\nelse\n  fib(x - 1) + fib(x - 2)\nend\n\n# good\ndef the_answer = 42\ndef get_x = @x\ndef square(x) = x * x\n\n# Not (so) good: has side effect\ndef set_x(x) = (@x = x)\ndef print_foo = puts(\"foo\")\n----\n\n=== Ambiguous Endless Method Definitions [[ambiguous-endless-method-definitions]]\n\nKeywords with lower precedence than `=` can appear ambiguous when used after an endless method definition. This includes `and`, `or`, and the modifier forms of `if`, `unless`, `while`, and `until`. In these cases, the code may appear to include these keywords as part of the method body, but instead they actually modify the method definition itself.\n\nIn these cases, prefer using a normal method over an endless method.\n\n[source,ruby]\n----\n# bad\ndef foo = true if bar\n\n# good - using a non-endless method is more explicit\ndef foo\n  true\nend if bar\n\n# ok - method body is explicit\ndef foo = (true if bar)\n\n# ok - method definition is explicit\n(def foo = true) if bar\n----\n\n=== Double Colons [[double-colons]]\n\nUse `::` only to reference constants (this includes classes and modules) and constructors (like `Array()` or `Nokogiri::HTML()`).\nDo not use `::` for regular method calls.\n\n[source,ruby]\n----\n# bad\nSomeClass::some_method\nsome_object::some_method\n\n# good\nSomeClass.some_method\nsome_object.some_method\nSomeModule::SomeClass::SOME_CONST\nSomeModule::SomeClass()\n----\n\n=== Colon Method Definition [[colon-method-definition]]\n\nDo not use `::` to define class methods.\n\n[source,ruby]\n----\n# bad\nclass Foo\n  def self::some_method\n  end\nend\n\n# good\nclass Foo\n  def self.some_method\n  end\nend\n----\n\n=== Method Definition Parentheses [[method-parens]]\n\nUse `def` with parentheses when there are parameters.\nOmit the parentheses when the method doesn't accept any parameters.\n\n[source,ruby]\n----\n# bad\ndef some_method()\n  # body omitted\nend\n\n# good\ndef some_method\n  # body omitted\nend\n\n# bad\ndef some_method_with_parameters param1, param2\n  # body omitted\nend\n\n# good\ndef some_method_with_parameters(param1, param2)\n  # body omitted\nend\n----\n\n=== Method Call Parentheses [[method-invocation-parens]][[method-call-parens]]\n\nUse parentheses around the arguments of method calls, especially if the first argument begins with an open parenthesis `(`, as in `f((3 + 2) + 1)`.\n\n[source,ruby]\n----\n# bad\nx = Math.sin y\n# good\nx = Math.sin(y)\n\n# bad\narray.delete e\n# good\narray.delete(e)\n\n# bad\ntemperance = Person.new 'Temperance', 30\n# good\ntemperance = Person.new('Temperance', 30)\n----\n\n==== Method Call with No Arguments [[method-invocation-parens-no-args]][[method-call-parens-no-args]]\n\nAlways omit parentheses for method calls with no arguments.\n\n[source,ruby]\n----\n# bad\nKernel.exit!()\n2.even?()\nfork()\n'test'.upcase()\n\n# good\nKernel.exit!\n2.even?\nfork\n'test'.upcase\n----\n\n==== Methods That Have \"keyword\" Status in Ruby [[method-invocation-parens-keyword]][[method-call-parens-keyword]]\n\nAlways omit parentheses for methods that have \"keyword\" status in Ruby.\n\nNOTE: Unfortunately, it's not exactly clear _which_ methods have \"keyword\" status.\nThere is agreement that declarative methods have \"keyword\" status.\nHowever, there's less agreement on which non-declarative methods, if any, have \"keyword\" status.\n\n===== Non-Declarative Methods That Have \"keyword\" Status in Ruby [[method-invocation-parens-non-declarative-keyword]][[method-call-parens-non-declarative-keyword]]\n\nFor non-declarative methods with \"keyword\" status (e.g., various `Kernel` instance methods), two styles are considered acceptable.\nBy far the most popular style is to omit parentheses.\nRationale: The code reads better, and method calls look more like keywords.\nA less-popular style, but still acceptable, is to include parentheses.\nRationale: The methods have ordinary semantics, so why treat them differently, and it's easier to achieve a uniform style by not worrying about which methods have \"keyword\" status.\nWhichever one you pick, apply it consistently.\n\n[source,ruby]\n----\n# good (most popular)\nputs temperance.age\nsystem 'ls'\nexit 1\n\n# also good (less popular)\nputs(temperance.age)\nsystem('ls')\nexit(1)\n----\n\n==== Using `super` with Arguments  [[super-with-args]]\n\nAlways use parentheses when calling `super` with arguments:\n\n[source,ruby]\n----\n# bad\nsuper name, age\n\n# good\nsuper(name, age)\n----\n\nIMPORTANT: When calling `super` without arguments, `super` and `super()` mean different things. Decide what is appropriate for your usage.\n\n=== Too Many Params [[too-many-params]]\n\nAvoid parameter lists longer than three or four parameters.\n\n[source,ruby]\n----\n# bad\ndef create_user(first_name, last_name, email, phone, address, age)\n  # ...\nend\n\n# good\ndef create_user(first_name, last_name, email:, phone: nil, address: nil, age: nil)\n  # ...\nend\n----\n\n=== Optional Arguments [[optional-arguments]]\n\nDefine optional arguments at the end of the list of arguments.\nRuby has some unexpected results when calling methods that have optional arguments at the front of the list.\n\n[source,ruby]\n----\n# bad\ndef some_method(a = 1, b = 2, c, d)\n  puts \"#{a}, #{b}, #{c}, #{d}\"\nend\n\nsome_method('w', 'x') # => '1, 2, w, x'\nsome_method('w', 'x', 'y') # => 'w, 2, x, y'\nsome_method('w', 'x', 'y', 'z') # => 'w, x, y, z'\n\n# good\ndef some_method(c, d, a = 1, b = 2)\n  puts \"#{a}, #{b}, #{c}, #{d}\"\nend\n\nsome_method('w', 'x') # => '1, 2, w, x'\nsome_method('w', 'x', 'y') # => 'y, 2, w, x'\nsome_method('w', 'x', 'y', 'z') # => 'y, z, w, x'\n----\n\n=== Keyword Arguments Order\n\nPut required keyword arguments before optional keyword arguments. Otherwise, it's much harder to spot optional keyword arguments there, if they're hidden somewhere in the middle.\n\n[source,ruby]\n----\n# bad\ndef some_method(foo: false, bar:, baz: 10)\n  # body omitted\nend\n\n# good\ndef some_method(bar:, foo: false, baz: 10)\n  # body omitted\nend\n----\n\n=== Boolean Keyword Arguments [[boolean-keyword-arguments]]\n\nUse keyword arguments when passing a boolean argument to a method.\n\n[source,ruby]\n----\n# bad\ndef some_method(bar = false)\n  puts bar\nend\n\n# bad - common hack before keyword args were introduced\ndef some_method(options = {})\n  bar = options.fetch(:bar, false)\n  puts bar\nend\n\n# good\ndef some_method(bar: false)\n  puts bar\nend\n\nsome_method            # => false\nsome_method(bar: true) # => true\n----\n\n=== Keyword Arguments vs Optional Arguments [[keyword-arguments-vs-optional-arguments]]\n\nPrefer keyword arguments over optional arguments.\n\n[source,ruby]\n----\n# bad\ndef some_method(a, b = 5, c = 1)\n  # body omitted\nend\n\n# good\ndef some_method(a, b: 5, c: 1)\n  # body omitted\nend\n----\n\n=== Keyword Arguments vs Option Hashes [[keyword-arguments-vs-option-hashes]]\n\nUse keyword arguments instead of option hashes.\n\n[source,ruby]\n----\n# bad\ndef some_method(options = {})\n  bar = options.fetch(:bar, false)\n  puts bar\nend\n\n# good\ndef some_method(bar: false)\n  puts bar\nend\n----\n\n=== Merging Keyword Arguments [[merging-keyword-arguments]]\n\nWhen passing an existing hash as keyword arguments, add additional arguments directly rather than using `merge`.\n\n[source,ruby]\n----\n# bad\nsome_method(**opts.merge(foo: true))\n\n# good\nsome_method(**opts, foo: true)\n----\n\n=== Arguments Forwarding [[arguments-forwarding]]\n\nUse Ruby 2.7's arguments forwarding.\n\n[source,ruby]\n----\n# bad\ndef some_method(*args, &block)\n  other_method(*args, &block)\nend\n\n# bad\ndef some_method(*args, **kwargs, &block)\n  other_method(*args, **kwargs, &block)\nend\n\n# bad\n# Please note that it can cause unexpected incompatible behavior\n# because `...` forwards block also.\n# https://github.com/rubocop/rubocop/issues/7549\ndef some_method(*args)\n  other_method(*args)\nend\n\n# good\ndef some_method(...)\n  other_method(...)\nend\n----\n\n=== Block Forwarding\n\nUse Ruby 3.1's anonymous block forwarding.\n\nIn most cases, block argument is given name similar to `&block` or `&proc`. Their names have no information and `&` will be sufficient for syntactic meaning.\n\n[source,ruby]\n----\n# bad\ndef some_method(&block)\n  other_method(&block)\nend\n\n# good\ndef some_method(&)\n  other_method(&)\nend\n----\n\n=== Private Global Methods [[private-global-methods]]\n\nIf you really need \"global\" methods, add them to Kernel and make them private.\n\n[source,ruby]\n----\n# bad\ndef global_helper\n  # ...\nend\n\n# good\nmodule Kernel\n  private\n\n  def global_helper\n    # ...\n  end\nend\n----\n\n== Classes & Modules\n\n=== Consistent Classes [[consistent-classes]]\n\nUse a consistent structure in your class definitions.\n\n[source,ruby]\n----\nclass Person\n  # extend/include/prepend go first\n  extend SomeModule\n  include AnotherModule\n  prepend YetAnotherModule\n\n  # inner classes\n  class CustomError < StandardError\n  end\n\n  # constants are next\n  SOME_CONSTANT = 20\n\n  # afterwards we have attribute macros\n  attr_reader :name\n\n  # followed by other macros (if any)\n  validates :name\n\n  # public class methods are next in line\n  def self.some_method\n  end\n\n  # initialization goes between class methods and other instance methods\n  def initialize\n  end\n\n  # followed by other public instance methods\n  def some_method\n  end\n\n  # protected and private methods are grouped near the end\n  protected\n\n  def some_protected_method\n  end\n\n  private\n\n  def some_private_method\n  end\nend\n----\n\n=== Mixin Grouping [[mixin-grouping]]\n\nSplit multiple mixins into separate statements.\n\n[source,ruby]\n----\n# bad\nclass Person\n  include Foo, Bar\nend\n\n# good\nclass Person\n  # multiple mixins go in separate statements\n  include Foo\n  include Bar\nend\n----\n\n=== Single-line Classes [[single-line-classes]]\n\nPrefer a two-line format for class definitions with no body. It is easiest to read, understand, and modify.\n\n[source,ruby]\n----\n# bad\nFooError = Class.new(StandardError)\n\n# okish\nclass FooError < StandardError; end\n\n# ok\nclass FooError < StandardError\nend\n----\n\nNOTE: Many editors/tools will fail to understand properly the usage of `Class.new`.\nSomeone trying to locate the class definition might try a grep \"class FooError\".\nA final difference is that the name of your class is not available to the `inherited`\ncallback of the base class with the `Class.new` form.\nIn general it's better to stick to the basic two-line style.\n\n=== File Classes [[file-classes]]\n\nDon't nest multi-line classes within classes.\nTry to have such nested classes each in their own file in a folder named like the containing class.\n\n[source,ruby]\n----\n# bad\n\n# foo.rb\nclass Foo\n  class Bar\n    # 30 methods inside\n  end\n\n  class Car\n    # 20 methods inside\n  end\n\n  # 30 methods inside\nend\n\n# good\n\n# foo.rb\nclass Foo\n  # 30 methods inside\nend\n\n# foo/bar.rb\nclass Foo\n  class Bar\n    # 30 methods inside\n  end\nend\n\n# foo/car.rb\nclass Foo\n  class Car\n    # 20 methods inside\n  end\nend\n----\n\n=== Namespace Definition [[namespace-definition]]\n\nDefine (and reopen) namespaced classes and modules using explicit nesting.\nUsing the scope resolution operator can lead to surprising constant lookups due to Ruby's https://cirw.in/blog/constant-lookup.html[lexical scoping], which depends on the module nesting at the point of definition.\n\n[source,ruby]\n----\nmodule Utilities\n  class Queue\n  end\nend\n\n# bad\nclass Utilities::Store\n  Module.nesting # => [Utilities::Store]\n\n  def initialize\n    # Refers to the top level ::Queue class because Utilities isn't in the\n    # current nesting chain.\n    @queue = Queue.new\n  end\nend\n\n# good\nmodule Utilities\n  class WaitingList\n    Module.nesting # => [Utilities::WaitingList, Utilities]\n\n    def initialize\n      @queue = Queue.new # Refers to Utilities::Queue\n    end\n  end\nend\n----\n\n=== Modules vs Classes [[modules-vs-classes]]\n\nPrefer modules to classes with only class methods.\nClasses should be used only when it makes sense to create instances out of them.\n\n[source,ruby]\n----\n# bad\nclass SomeClass\n  def self.some_method\n    # body omitted\n  end\n\n  def self.some_other_method\n    # body omitted\n  end\nend\n\n# good\nmodule SomeModule\n  module_function\n\n  def some_method\n    # body omitted\n  end\n\n  def some_other_method\n    # body omitted\n  end\nend\n----\n\n=== `module_function` [[module-function]]\n\nPrefer the use of `module_function` over `extend self` when you want to turn a module's instance methods into class methods.\n\n[source,ruby]\n----\n# bad\nmodule Utilities\n  extend self\n\n  def parse_something(string)\n    # do stuff here\n  end\n\n  def other_utility_method(number, string)\n    # do some more stuff\n  end\nend\n\n# good\nmodule Utilities\n  module_function\n\n  def parse_something(string)\n    # do stuff here\n  end\n\n  def other_utility_method(number, string)\n    # do some more stuff\n  end\nend\n----\n\n=== Liskov [[liskov]]\n\nWhen designing class hierarchies make sure that they conform to the https://en.wikipedia.org/wiki/Liskov_substitution_principle[Liskov Substitution Principle].\n\n=== SOLID design [[solid-design]]\n\nTry to make your classes as https://en.wikipedia.org/wiki/SOLID[SOLID] as possible.\n\n=== Define `to_s` [[define-to-s]]\n\nAlways supply a proper `to_s` method for classes that represent domain objects.\n\n[source,ruby]\n----\nclass Person\n  attr_reader :first_name, :last_name\n\n  def initialize(first_name, last_name)\n    @first_name = first_name\n    @last_name = last_name\n  end\n\n  def to_s\n    \"#{first_name} #{last_name}\"\n  end\nend\n----\n\n=== `attr` Family [[attr_family]]\n\nUse the `attr` family of functions to define trivial accessors or mutators.\n\n[source,ruby]\n----\n# bad\nclass Person\n  def initialize(first_name, last_name)\n    @first_name = first_name\n    @last_name = last_name\n  end\n\n  def first_name\n    @first_name\n  end\n\n  def last_name\n    @last_name\n  end\nend\n\n# good\nclass Person\n  attr_reader :first_name, :last_name\n\n  def initialize(first_name, last_name)\n    @first_name = first_name\n    @last_name = last_name\n  end\nend\n----\n\n=== Accessor/Mutator Method Names [[accessor_mutator_method_names]]\n\nFor accessors and mutators, avoid prefixing method names with `get_` and `set_`.\nIt is a Ruby convention to use attribute names for accessors (readers) and `attr_name=` for mutators (writers).\n\n[source,ruby]\n----\n# bad\nclass Person\n  def get_name\n    \"#{@first_name} #{@last_name}\"\n  end\n\n  def set_name(name)\n    @first_name, @last_name = name.split(' ')\n  end\nend\n\n# good\nclass Person\n  def name\n    \"#{@first_name} #{@last_name}\"\n  end\n\n  def name=(name)\n    @first_name, @last_name = name.split(' ')\n  end\nend\n----\n\n=== `attr` [[attr]]\n\nAvoid the use of `attr`.\nUse `attr_reader` and `attr_accessor` instead.\n\n[source,ruby]\n----\n# bad - creates a single attribute accessor (deprecated in Ruby 1.9)\nattr :something, true\nattr :one, :two, :three # behaves as attr_reader\n\n# good\nattr_accessor :something\nattr_reader :one, :two, :three\n----\n\n=== `Struct.new` [[struct-new]]\n\nConsider using `Struct.new`, which defines the trivial accessors, constructor and comparison operators for you.\n\n[source,ruby]\n----\n# good\nclass Person\n  attr_accessor :first_name, :last_name\n\n  def initialize(first_name, last_name)\n    @first_name = first_name\n    @last_name = last_name\n  end\nend\n\n# better\nPerson = Struct.new(:first_name, :last_name) do\nend\n----\n\n=== Don't Extend `Struct.new` [[no-extend-struct-new]]\n\nDon't extend an instance initialized by `Struct.new`.\nExtending it introduces a superfluous class level and may also introduce weird errors if the file is required multiple times.\n\n[source,ruby]\n----\n# bad\nclass Person < Struct.new(:first_name, :last_name)\nend\n\n# good\nPerson = Struct.new(:first_name, :last_name)\n----\n\n=== Don't Extend `Data.define` [[no-extend-data-define]]\n\nDon't extend an instance initialized by `Data.define`.\nExtending it introduces a superfluous class level.\n\n[source,ruby]\n----\n# bad\nclass Person < Data.define(:first_name, :last_name)\nend\n\nPerson.ancestors\n# => [Person, #<Class:0x0000000105abed88>, Data, Object, (...)]\n\n# good\nPerson = Data.define(:first_name, :last_name)\n\nPerson.ancestors\n# => [Person, Data, Object, (...)]\n----\n\n=== Duck Typing [[duck-typing]]\n\nPrefer https://en.wikipedia.org/wiki/Duck_typing[duck-typing] over inheritance.\n\n[source,ruby]\n----\n# bad\nclass Animal\n  # abstract method\n  def speak\n  end\nend\n\n# extend superclass\nclass Duck < Animal\n  def speak\n    puts 'Quack! Quack'\n  end\nend\n\n# extend superclass\nclass Dog < Animal\n  def speak\n    puts 'Bau! Bau!'\n  end\nend\n\n# good\nclass Duck\n  def speak\n    puts 'Quack! Quack'\n  end\nend\n\nclass Dog\n  def speak\n    puts 'Bau! Bau!'\n  end\nend\n----\n\n=== No Class Vars [[no-class-vars]]\n\nAvoid the usage of class (`@@`) variables due to their \"nasty\" behavior in inheritance.\n\n[source,ruby]\n----\nclass Parent\n  @@class_var = 'parent'\n\n  def self.print_class_var\n    puts @@class_var\n  end\nend\n\nclass Child < Parent\n  @@class_var = 'child'\nend\n\nParent.print_class_var # => will print 'child'\n----\n\nAs you can see all the classes in a class hierarchy actually share one class variable.\nClass instance variables should usually be preferred over class variables.\n\n=== Leverage Access Modifiers (e.g. `private` and `protected`) [[visibility]]\n\nAssign proper visibility levels to methods (`private`, `protected`) in accordance with their intended usage.\nDon't go off leaving everything `public` (which is the default).\n\n=== Access Modifiers Indentation [[indent-public-private-protected]]\n\nIndent the `public`, `protected`, and `private` methods as much as the method definitions they apply to.\nLeave one blank line above the visibility modifier and one blank line below in order to emphasize that it applies to all methods below it.\n\n[source,ruby]\n----\n# good\nclass SomeClass\n  def public_method\n    # some code\n  end\n\n  private\n\n  def private_method\n    # some code\n  end\n\n  def another_private_method\n    # some code\n  end\nend\n----\n\n=== Defining Class Methods [[def-self-class-methods]]\n\nUse `def self.method` to define class methods.\nThis makes the code easier to refactor since the class name is not repeated.\n\n[source,ruby]\n----\nclass TestClass\n  # bad\n  def TestClass.some_method\n    # body omitted\n  end\n\n  # good\n  def self.some_other_method\n    # body omitted\n  end\n\n  # Also possible and convenient when you\n  # have to define many class methods.\n  class << self\n    def first_method\n      # body omitted\n    end\n\n    def second_method_etc\n      # body omitted\n    end\n  end\nend\n----\n\n=== Alias Method Lexically [[alias-method-lexically]]\n\nPrefer `alias` when aliasing methods in lexical class scope as the resolution of `self` in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.\n\n[source,ruby]\n----\nclass Westerner\n  def first_name\n    @names.first\n  end\n\n  alias given_name first_name\nend\n----\n\nSince `alias`, like `def`, is a keyword, prefer bareword arguments over symbols or strings.\nIn other words, do `alias foo bar`, not `alias :foo :bar`.\n\nAlso be aware of how Ruby handles aliases and inheritance: an alias references the method that was resolved at the time the alias was defined; it is not dispatched dynamically.\n\n[source,ruby]\n----\nclass Fugitive < Westerner\n  def first_name\n    'Nobody'\n  end\nend\n----\n\nIn this example, `Fugitive#given_name` would still call the original `Westerner#first_name` method, not `Fugitive#first_name`.\nTo override the behavior of `Fugitive#given_name` as well, you'd have to redefine it in the derived class.\n\n[source,ruby]\n----\nclass Fugitive < Westerner\n  def first_name\n    'Nobody'\n  end\n\n  alias given_name first_name\nend\n----\n\n=== `alias_method` [[alias-method]]\n\nAlways use `alias_method` when aliasing methods of modules, classes, or singleton classes at runtime, as the lexical scope of `alias` leads to unpredictability in these cases.\n\n[source,ruby]\n----\nmodule Mononymous\n  def self.included(other)\n    other.class_eval { alias_method :full_name, :given_name }\n  end\nend\n\nclass Sting < Westerner\n  include Mononymous\nend\n----\n\n=== Class and `self` [[class-and-self]]\n\nWhen class (or module) methods call other such methods, omit the use of a leading `self` or own name followed by a `.` when calling other such methods.\nThis is often seen in \"service classes\" or other similar concepts where a class is treated as though it were a function.\nThis convention tends to reduce repetitive boilerplate in such classes.\n\n[source,ruby]\n----\nclass TestClass\n  # bad - more work when class renamed/method moved\n  def self.call(param1, param2)\n    TestClass.new(param1).call(param2)\n  end\n\n  # bad - more verbose than necessary\n  def self.call(param1, param2)\n    self.new(param1).call(param2)\n  end\n\n  # good\n  def self.call(param1, param2)\n    new(param1).call(param2)\n  end\n\n  # ...other methods...\nend\n----\n\n=== Defining Constants within a Block [[no-constant-definition-in-block]]\n\nDo not define constants within a block, since the block's scope does not isolate or namespace the constant in any way.\n\nDefine the constant outside of the block instead, or use a variable or method if defining the constant in the outer scope would be problematic.\n\n[source,ruby]\n----\n# bad - FILES_TO_LINT is now defined globally\ntask :lint do\n  FILES_TO_LINT = Dir['lib/*.rb']\n  # ...\nend\n\n# good - files_to_lint is only defined inside the block\ntask :lint do\n  files_to_lint = Dir['lib/*.rb']\n  # ...\nend\n----\n\n== Classes: Constructors\n\n=== Factory Methods [[factory-methods]]\n\nConsider adding factory methods to provide additional sensible ways to create instances of a particular class.\n\n[source,ruby]\n----\nclass Person\n  def self.create(options_hash)\n    # body omitted\n  end\nend\n----\n\n=== Disjunctive Assignment in Constructor [[disjunctive-assignment-in-constructor]]\n\nIn constructors, avoid unnecessary disjunctive assignment (`||=`) of instance variables.\nPrefer plain assignment.\nIn ruby, instance variables (beginning with an `@`) are nil until assigned a value, so in most cases the disjunction is unnecessary.\n\n[source,ruby]\n----\n# bad\ndef initialize\n  @x ||= 1\nend\n\n# good\ndef initialize\n  @x = 1\nend\n----\n\n== Comments\n\n[quote, Steve McConnell]\n____\nGood code is its own best documentation.\nAs you're about to add a comment, ask yourself, \"How can I improve the code so that this comment isn't needed?\".\nImprove the code and then document it to make it even clearer.\n____\n\n=== No Comments [[no-comments]]\n\nWrite self-documenting code and ignore the rest of this section. Seriously!\n\n=== Rationale Comments [[rationale-comments]]\n\nIf the _how_ can be made self-documenting, but not the _why_ (e.g. the code works around non-obvious library behavior, or implements an algorithm from an academic paper), add a comment explaining the rationale behind the code.\n\n[source,ruby]\n----\n# bad\n\nx = BuggyClass.something.dup\n\ndef compute_dependency_graph\n  ...30 lines of recursive graph merging...\nend\n\n# good\n\n# BuggyClass returns an internal object, so we have to dup it to modify it.\nx = BuggyClass.something.dup\n\n# This is algorithm 6.4(a) from Worf & Yar's _Amazing Graph Algorithms_ (2243).\ndef compute_dependency_graph\n  ...30 lines of recursive graph merging...\nend\n----\n\n=== English Comments [[english-comments]]\n\nWrite comments in English.\n\n=== Hash Space [[hash-space]]\n\nUse one space between the leading `#` character of the comment and the text of the comment.\n\n[source,ruby]\n----\n# bad\n#some comment\n\n# good\n# some comment\n----\n\n=== English Syntax [[english-syntax]]\n\nComments longer than a word are capitalized and use punctuation.\nUse https://en.wikipedia.org/wiki/Sentence_spacing[one space] after periods.\n\n=== No Superfluous Comments [[no-superfluous-comments]]\n\nAvoid superfluous comments.\n\n[source,ruby]\n----\n# bad\ncounter += 1 # Increments counter by one.\n----\n\n=== Comment Upkeep [[comment-upkeep]]\n\nKeep existing comments up-to-date.\nAn outdated comment is worse than no comment at all.\n\n=== Refactor, Don't Comment [[refactor-dont-comment]]\n\n[quote, old programmers maxim, 'https://eloquentruby.com/blog/2011/03/07/good-code-and-good-jokes/[through Russ Olsen]']\n____\nGood code is like a good joke: it needs no explanation.\n____\n\nAvoid writing comments to explain bad code.\nRefactor the code to make it self-explanatory.\n(\"Do or do not - there is no try.\" Yoda)\n\n== Comment Annotations\n\n=== Annotations Placement [[annotate-above]]\n\nAnnotations should usually be written on the line immediately above the relevant code.\n\n[source,ruby]\n----\n# bad\ndef bar\n  baz(:quux) # FIXME: This has crashed occasionally since v3.2.1.\nend\n\n# good\ndef bar\n  # FIXME: This has crashed occasionally since v3.2.1.\n  baz(:quux)\nend\n----\n\n=== Annotations Keyword Format [[annotate-keywords]]\n\nThe annotation keyword is followed by a colon and a space, then a note describing the problem.\n\n[source,ruby]\n----\n# bad\ndef bar\n  # FIXME This has crashed occasionally since v3.2.1.\n  baz(:quux)\nend\n\n# good\ndef bar\n  # FIXME: This has crashed occasionally since v3.2.1.\n  baz(:quux)\nend\n----\n\n=== Multi-line Annotations Indentation [[indent-annotations]]\n\nIf multiple lines are required to describe the problem, subsequent lines should be indented three spaces after the `#` (one general plus two for indentation purposes).\n\n[source,ruby]\n----\ndef bar\n  # FIXME: This has crashed occasionally since v3.2.1. It may\n  #   be related to the BarBazUtil upgrade.\n  baz(:quux)\nend\n----\n\n=== Inline Annotations [[rare-eol-annotations]]\n\nIn cases where the problem is so obvious that any documentation would be redundant, annotations may be left at the end of the offending line with no note.\nThis usage should be the exception and not the rule.\n\n[source,ruby]\n----\ndef bar\n  sleep 100 # OPTIMIZE\nend\n----\n\n=== `TODO` [[todo]]\n\nUse `TODO` to note missing features or functionality that should be added at a later date.\n\n=== `FIXME` [[fixme]]\n\nUse `FIXME` to note broken code that needs to be fixed.\n\n=== `OPTIMIZE` [[optimize]]\n\nUse `OPTIMIZE` to note slow or inefficient code that may cause performance problems.\n\n=== `HACK` [[hack]]\n\nUse `HACK` to note code smells where questionable coding practices were used and should be refactored away.\n\n=== `REVIEW` [[review]]\n\nUse `REVIEW` to note anything that should be looked at to confirm it is working as intended.\nFor example: `REVIEW: Are we sure this is how the client does X currently?`\n\n=== Document Annotations [[document-annotations]]\n\nUse other custom annotation keywords if it feels appropriate, but be sure to document them in your project's `README` or similar.\n\n== Magic Comments\n\n=== Magic Comments First [[magic-comments-first]]\n\nPlace magic comments above all code and documentation in a file (except shebangs, which are discussed next).\n\n[source,ruby]\n----\n# bad\n# Some documentation about Person\n\n# frozen_string_literal: true\nclass Person\nend\n\n# good\n# frozen_string_literal: true\n\n# Some documentation about Person\nclass Person\nend\n----\n\n=== Below Shebang [[below-shebang]]\n\nPlace magic comments below shebangs when they are present in a file.\n\n[source,ruby]\n----\n# bad\n# frozen_string_literal: true\n#!/usr/bin/env ruby\n\nApp.parse(ARGV)\n\n# good\n#!/usr/bin/env ruby\n# frozen_string_literal: true\n\nApp.parse(ARGV)\n----\n\n=== One Magic Comment per Line [[one-magic-comment-per-line]]\n\nUse one magic comment per line if you need multiple.\n\n[source,ruby]\n----\n# bad\n# -*- frozen_string_literal: true; encoding: ascii-8bit -*-\n\n# good\n# frozen_string_literal: true\n# encoding: ascii-8bit\n----\n\n=== Separate Magic Comments from Code [[separate-magic-comments-from-code]]\n\nSeparate magic comments from code and documentation with a blank line.\n\n[source,ruby]\n----\n# bad\n# frozen_string_literal: true\n# Some documentation for Person\nclass Person\n  # Some code\nend\n\n# good\n# frozen_string_literal: true\n\n# Some documentation for Person\nclass Person\n  # Some code\nend\n----\n\n== Collections\n\n=== Literal Array and Hash [[literal-array-hash]]\n\nPrefer literal array and hash creation notation (unless you need to pass parameters to their constructors, that is).\n\n[source,ruby]\n----\n# bad\narr = Array.new\nhash = Hash.new\n\n# good\narr = []\narr = Array.new(10)\nhash = {}\nhash = Hash.new(0)\n----\n\n=== `%w` [[percent-w]]\n\nPrefer `%w` to the literal array syntax when you need an array of words (non-empty strings without spaces and special characters in them).\nApply this rule only to arrays with two or more elements.\n\n[source,ruby]\n----\n# bad\nSTATES = ['draft', 'open', 'closed']\n\n# good\nSTATES = %w[draft open closed]\n----\n\n=== `%i` [[percent-i]]\n\nPrefer `%i` to the literal array syntax when you need an array of symbols (and you don't need to maintain Ruby 1.9 compatibility).\nApply this rule only to arrays with two or more elements.\n\n[source,ruby]\n----\n# bad\nSTATES = [:draft, :open, :closed]\n\n# good\nSTATES = %i[draft open closed]\n----\n\n=== No Trailing Array Commas [[no-trailing-array-commas]]\n\nAvoid comma after the last item of an `Array` or `Hash` literal, especially when the items are not on separate lines.\n\n[source,ruby]\n----\n# bad - easier to move/add/remove items, but still not preferred\nVALUES = [\n           1001,\n           2020,\n           3333,\n         ]\n\n# bad\nVALUES = [1001, 2020, 3333, ]\n\n# good\nVALUES = [1001, 2020, 3333]\n----\n\n=== No Gappy Arrays [[no-gappy-arrays]]\n\nAvoid the creation of huge gaps in arrays.\n\n[source,ruby]\n----\narr = []\narr[100] = 1 # now you have an array with lots of nils\n----\n\n=== `first` and `last` [[first-and-last]]\n\nWhen accessing the first or last element from an array, prefer `first` or `last` over `[0]` or `[-1]`.\n`first` and `last` take less effort to understand, especially for a less experienced Ruby programmer or someone from a language with different indexing semantics.\n\n[source,ruby]\n----\narr = [1, 2, 3]\n\n# ok\narr[0]  # => 1\narr[-1] # => 3\n\n# (arguably) better\narr.first # => 1\narr.last  # => 3\n\n# good - assignments can only be done via []=\narr[0] = 2\narr[-1] = 5\n----\n\n=== Set vs Array [[set-vs-array]]\n\nUse `Set` instead of `Array` when dealing with unique elements.\n`Set` implements a collection of unordered values with no duplicates.\nThis is a hybrid of ``Array``'s intuitive inter-operation facilities and ``Hash``'s fast lookup.\n\n=== Symbols as Keys [[symbols-as-keys]]\n\nPrefer symbols instead of strings as hash keys.\n\n[source,ruby]\n----\n# bad\nhash = { 'one' => 1, 'two' => 2, 'three' => 3 }\n\n# good\nhash = { one: 1, two: 2, three: 3 }\n----\n\n=== No Mutable Keys [[no-mutable-keys]]\n\nAvoid the use of mutable objects as hash keys.\n\n[source,ruby]\n----\n# bad\nhash = { 'name' => 'John' }\n\n# good\nhash = { name: 'John' }\n\n# good - frozen string key when symbols won't do\nhash = { 'name'.freeze => 'John' }\n----\n\n=== No Mutable Defaults [[no-mutable-defaults]]\n\nAvoid the use of shared mutable objects as hash default values.\n\nCreating a Hash in such a way will share the default value\nacross all keys, causing unexpected behavior when modifying it.\n\nFor example, when the Hash was created with an Array as the argument,\ncalling `hash[:foo] << 'bar'` will also change the value of all\nother keys that have not been explicitly assigned to.\n\n[source,ruby]\n----\n# bad\nHash.new([])\nHash.new({})\nHash.new(Array.new)\nHash.new(Hash.new)\n\n# okay -- beware this will silently discard mutations and only remember assignments\nHash.new { Array.new }\nHash.new { Hash.new }\nHash.new { {} }\nHash.new { [] }\n\n# good - frozen solution will raise an error when mutation is attempted\nHash.new([].freeze)\nHash.new({}.freeze)\n\n# good - using a proc will create a new object for each key\nh = Hash.new\nh.default_proc = ->(h, k) { [] }\nh.default_proc = ->(h, k) { {} }\n\n# good - using a block will create a new object for each key\nHash.new { |h, k| h[k] = [] }\nHash.new { |h, k| h[k] = {} }\n----\n\n=== Hash Literals [[hash-literals]]\n\nUse the Ruby 1.9 hash literal syntax when your hash keys are symbols.\n\n[source,ruby]\n----\n# bad\nhash = { :one => 1, :two => 2, :three => 3 }\n\n# good\nhash = { one: 1, two: 2, three: 3 }\n----\n\n=== Hash Literal Values\n\nUse the Ruby 3.1 hash literal value syntax when your hash key and value are the same.\n\n[source,ruby]\n----\n# bad\nhash = { one: one, two: two, three: three }\n\n# good\nhash = { one:, two:, three: }\n----\n\n=== Hash Literal as Last Array Item [[hash-literal-as-last-array-item]]\n\nWrap hash literal in braces if it is a last array item.\n\n[source,ruby]\n----\n# bad\n[1, 2, one: 1, two: 2]\n\n# good\n[1, 2, { one: 1, two: 2 }]\n----\n\n=== No Mixed Hash Syntaxes [[no-mixed-hash-syntaxes]]\n\nDon't mix the Ruby 1.9 hash syntax with hash rockets in the same hash literal.\nWhen you've got keys that are not symbols stick to the hash rockets syntax.\n\n[source,ruby]\n----\n# bad\n{ a: 1, 'b' => 2 }\n\n# good\n{ :a => 1, 'b' => 2 }\n----\n\n=== Avoid Hash[] constructor [[avoid-hash-constructor]]\n\n`Hash::[]` was a pre-Ruby 2.1 way of constructing hashes from arrays of key-value pairs,\nor from a flat list of keys and values. It has an obscure semantic and looks cryptic in code.\nSince Ruby 2.1, `Enumerable#to_h` can be used to construct a hash from a list of key-value pairs,\nand it should be preferred. Instead of `Hash[]` with a list of literal keys and values,\njust a hash literal should be preferred.\n\n[source,ruby]\n----\n# bad\nHash[ary]\nHash[a, b, c, d]\n\n# good\nary.to_h\n{a => b, c => d}\n----\n\n=== `Hash#key?` [[hash-key]]\n\nUse `Hash#key?` instead of `Hash#has_key?` and `Hash#value?` instead of `Hash#has_value?`.\n\n[source,ruby]\n----\n# bad\nhash.has_key?(:test)\nhash.has_value?(value)\n\n# good\nhash.key?(:test)\nhash.value?(value)\n----\n\n=== `Hash#each` [[hash-each]]\n\nUse `Hash#each_key` instead of `Hash#keys.each` and `Hash#each_value` instead of `Hash#values.each`.\n\n[source,ruby]\n----\n# bad\nhash.keys.each { |k| p k }\nhash.values.each { |v| p v }\nhash.each { |k, _v| p k }\nhash.each { |_k, v| p v }\n\n# good\nhash.each_key { |k| p k }\nhash.each_value { |v| p v }\n----\n\n=== `Hash#fetch` [[hash-fetch]]\n\nUse `Hash#fetch` when dealing with hash keys that should be present.\n\n[source,ruby]\n----\nheroes = { batman: 'Bruce Wayne', superman: 'Clark Kent' }\n# bad - if we make a mistake we might not spot it right away\nheroes[:batman] # => 'Bruce Wayne'\nheroes[:supermann] # => nil\n\n# good - fetch raises a KeyError making the problem obvious\nheroes.fetch(:supermann)\n----\n\n=== `Hash#fetch` defaults [[hash-fetch-defaults]]\n\nIntroduce default values for hash keys via `Hash#fetch` as opposed to using custom logic.\n\n[source,ruby]\n----\nbatman = { name: 'Bruce Wayne', is_evil: false }\n\n# bad - if we just use || operator with falsey value we won't get the expected result\nbatman[:is_evil] || true # => true\n\n# good - fetch works correctly with falsey values\nbatman.fetch(:is_evil, true) # => false\n----\n\n=== Use Hash Blocks [[use-hash-blocks]]\n\nPrefer the use of the block instead of the default value in `Hash#fetch` if the code that has to be evaluated may have side effects or be expensive.\n\n[source,ruby]\n----\nbatman = { name: 'Bruce Wayne' }\n\n# bad - if we use the default value, we eager evaluate it\n# so it can slow the program down if done multiple times\nbatman.fetch(:powers, obtain_batman_powers) # obtain_batman_powers is an expensive call\n\n# good - blocks are lazy evaluated, so only triggered in case of KeyError exception\nbatman.fetch(:powers) { obtain_batman_powers }\n----\n\n=== `Hash#values_at` and `Hash#fetch_values` [[hash-values-at-and-hash-fetch-values]]\n\nUse `Hash#values_at` or `Hash#fetch_values` when you need to retrieve several values consecutively from a hash.\n\n[source,ruby]\n----\n# bad\nemail = data['email']\nusername = data['nickname']\n\n# bad\nkeys = %w[email nickname].freeze\nemail, username = keys.map { |key| data[key] }\n\n# good\nemail, username = data.values_at('email', 'nickname')\n\n# also good\nemail, username = data.fetch_values('email', 'nickname')\n----\n\n=== `Hash#transform_keys` and `Hash#transform_values` [[hash-transform-methods]]\n\nPrefer `transform_keys` or `transform_values` over `each_with_object` or `map` when transforming just the keys or just the values of a hash.\n\n[source,ruby]\n----\n# bad\n{a: 1, b: 2}.each_with_object({}) { |(k, v), h| h[k] = v * v }\n{a: 1, b: 2}.map { |k, v| [k.to_s, v] }.to_h\n\n# good\n{a: 1, b: 2}.transform_values { |v| v * v }\n{a: 1, b: 2}.transform_keys { |k| k.to_s }\n----\n\n=== Ordered Hashes [[ordered-hashes]]\n\nRely on the fact that as of Ruby 1.9 hashes are ordered.\n\n=== No Modifying Collections [[no-modifying-collections]]\n\nDo not modify a collection while traversing it.\n\n[source,ruby]\n----\n# bad\nnumbers = [1, 2, 3, 4, 5]\nnumbers.each { |n| numbers.delete(n) if n.even? }\n\n# good\nnumbers = [1, 2, 3, 4, 5]\nodd_numbers = numbers.reject(&:even?)\n----\n\n=== Accessing Elements Directly [[accessing-elements-directly]]\n\nWhen accessing elements of a collection, avoid direct access via `[n]` by using an alternate form of the reader method if it is supplied.\nThis guards you from calling `[]` on `nil`.\n\n[source,ruby]\n----\n# bad\nRegexp.last_match[1]\n\n# good\nRegexp.last_match(1)\n----\n\n=== Provide Alternate Accessor to Collections [[provide-alternate-accessor-to-collections]]\n\nWhen providing an accessor for a collection, provide an alternate form to save users from checking for `nil` before accessing an element in the collection.\n\n[source,ruby]\n----\n# bad\ndef awesome_things\n  @awesome_things\nend\n\n# good\ndef awesome_things(index = nil)\n  if index && @awesome_things\n    @awesome_things[index]\n  else\n    @awesome_things\n  end\nend\n----\n\n=== `map`/`find`/`select`/`reduce`/`include?`/`size` [[map-find-select-reduce-include-size]]\n\nPrefer `map` over `collect`, `find` over `detect`, `select` over `find_all`, `reduce` over `inject`, `include?` over `member?` and `size` over `length`.\nThis is not a hard requirement; if the use of the alias enhances readability, it's ok to use it.\nThe rhyming methods are inherited from Smalltalk and are not common in other programming languages.\nThe reason the use of `select` is encouraged over `find_all` is that it goes together nicely with `reject` and its name is pretty self-explanatory.\n\n[source,ruby]\n----\n# bad\nitems.collect { |item| item.name }\nitems.detect(&:active?)\nitems.find_all(&:valid?)\nitems.inject(0) { |sum, i| sum + i }\nitems.member?(value)\nitems.length\n\n# good\nitems.map { |item| item.name }\nitems.find(&:active?)\nitems.select(&:valid?)\nitems.reduce(0) { |sum, i| sum + i }\nitems.include?(value)\nitems.size\n----\n\n=== `count` vs `size` [[count-vs-size]]\n\nDon't use `count` as a substitute for `size`.\nFor `Enumerable` objects other than `Array` it will iterate the entire collection in order to determine its size.\n\n[source,ruby]\n----\n# bad\nsome_hash.count\n\n# good\nsome_hash.size\n----\n\n=== `flat_map` [[flat-map]]\n\nUse `flat_map` instead of `map` + `flatten`.\nThis does not apply for arrays with a depth greater than 2, i.e. if `users.first.songs == ['a', ['b','c']]`, then use `map + flatten` rather than `flat_map`.\n`flat_map` flattens the array by 1, whereas `flatten` flattens it all the way.\n\n[source,ruby]\n----\n# bad\nall_songs = users.map(&:songs).flatten.uniq\n\n# good\nall_songs = users.flat_map(&:songs).uniq\n----\n\n=== `reverse_each` [[reverse-each]]\n\nPrefer `reverse_each` to `reverse.each` because some classes that `include Enumerable` will provide an efficient implementation.\nEven in the worst case where a class does not provide a specialized implementation, the general implementation inherited from `Enumerable` will be at least as efficient as using `reverse.each`.\n\n[source,ruby]\n----\n# bad\narray.reverse.each { ... }\n\n# good\narray.reverse_each { ... }\n----\n\n=== `Object#yield_self` vs `Object#then` [[object-yield-self-vs-object-then]]\n\nThe method `Object#then` is preferred over `Object#yield_self`, since the name `then` states the intention, not the behavior. This makes the resulting code easier to read.\n\n[source,ruby]\n----\n# bad\nobj.yield_self { |x| x.do_something }\n\n# good\nobj.then { |x| x.do_something }\n----\n\nNOTE: You can read more about the rationale behind this guideline https://bugs.ruby-lang.org/issues/14594[here].\n\n=== Slicing with Ranges\n\nSlicing arrays with ranges to extract some of their elements (e.g `ary[2..5]`) is a popular technique. Below you'll find a few small considerations to keep in mind when using it.\n\n* `[0..-1]` in `ary[0..-1]` is redundant and simply synonymous with `ary`.\n\n[source,ruby]\n----\n# bad - you're selecting all the elements of the array\nary[0..-1]\nary[0..nil]\nary[0...nil]\n\n# good\nary\n----\n\n* Ruby 2.6 introduced endless ranges, which provide an easier way to describe a slice going all the way to the end of an array.\n\n[source,ruby]\n----\n# bad - hard to process mentally\nary[1..-1]\nary[1..nil]\n\n# good - easier to read and more concise\nary[1..]\n----\n\n* Ruby 2.7 introduced beginless ranges, which are also handy in slicing. However, unlike the somewhat obscure `-1` in `ary[1..-1]`, the `0` in `ary[0..42]` is clear\nas a starting point. In fact, changing it to `ary[..42]` could potentially make it less readable. Therefore, using code like `ary[0..42]`\nis fine. On the other hand, `ary[nil..42]` should be replaced with `ary[..42]` or `arr[0..42]`.\n\n[source,ruby]\n----\n# bad - hard to process mentally\nary[nil..42]\n\n# good - easier to read\nary[..42]\nary[0..42]\n----\n\n=== Collection querying [[collection-querying]]\n\nWhen possible, use https://docs.ruby-lang.org/en/master/Enumerable.html#module-Enumerable-label-Methods+for+Querying[predicate methods from `Enumerable`] rather than expressions with `#count`, `#length` or `#size`.\n\nQuerying methods express the intention more clearly and are more performant in some cases. For example, `articles.any?(&:published?)` is more readable than `articles.count(&:published?) > 0` and also more performant because `#any?` stops execution as soon as the first published article is found, while `#count` traverses the whole collection.\n\n[source,ruby]\n----\n# bad\narray.count > 0\narray.length > 0\narray.size > 0\n\narray.count(&:something).positive?\n\narray.count(&:something) == 0\n\narray.count(&:something) == 1\n\n# good\narray.any?\n\narray.any?(&:something)\n\narray.none?(&:something)\n\narray.one?(&:something)\n----\n\n[NOTE]\n--\nPredicate methods without arguments can't replace `count` expressions when collection includes falsey values:\n[source,ruby]\n----\n[nil, false].any?\n# => false\n\n[nil, false].none?\n# => true\n\n[nil].one?\n# => false\n\n[false].one?\n# => false\n----\n--\n\n== Numbers\n\n=== Underscores in Numerics [[underscores-in-numerics]]\n\nAdd underscores to large numeric literals to improve their readability.\n\n[source,ruby]\n----\n# bad - how many 0s are there?\nnum = 1000000\n\n# good - much easier to parse for the human brain\nnum = 1_000_000\n----\n\n=== Numeric Literal Prefixes [[numeric-literal-prefixes]]\n\nPrefer lowercase letters for numeric literal prefixes.\n`0o` for octal, `0x` for hexadecimal and `0b` for binary.\nDo not use `0d` prefix for decimal literals.\n\n[source,ruby]\n----\n# bad\nnum = 01234\nnum = 0O1234\nnum = 0X12AB\nnum = 0B10101\nnum = 0D1234\nnum = 0d1234\n\n# good - easier to separate digits from the prefix\nnum = 0o1234\nnum = 0x12AB\nnum = 0b10101\nnum = 1234\n----\n\n=== Integer Type Checking [[integer-type-checking]]\n\nUse `Integer` to check the type of an integer number.\nSince `Fixnum` is platform-dependent, checking against it will return different results on 32-bit and 64-bit machines.\n\n[source,ruby]\n----\ntimestamp = Time.now.to_i\n\n# bad\ntimestamp.is_a?(Fixnum)\ntimestamp.is_a?(Bignum)\n\n# good\ntimestamp.is_a?(Integer)\n----\n\n=== Random Numbers [[random-numbers]]\n\nPrefer to use ranges when generating random numbers instead of integers with offsets, since it clearly states your intentions.\nImagine simulating a roll of a dice:\n\n[source,ruby]\n----\n# bad\nrand(6) + 1\n\n# good\nrand(1..6)\n----\n\n=== Float Division [[float-division]]\n\nWhen performing float-division on two integers, either use `fdiv` or convert one of the integers to float.\n\n[source,ruby]\n----\n# bad\na.to_f / b.to_f\n\n# good\na.to_f / b\na / b.to_f\na.fdiv(b)\n----\n\n=== Float Comparison [[float-comparison]]\n\nAvoid (in)equality comparisons of floats as they are unreliable.\n\nFloating point values are inherently inaccurate, and comparing them for exact equality is almost never the desired semantics. Comparison via the `==/!=` operators checks floating-point value representation to be exactly the same, which is very unlikely if you perform any arithmetic operations involving precision loss.\n\n[source,ruby]\n----\n# bad\nx == 0.1\nx != 0.1\n\n# good - using BigDecimal\nx.to_d == 0.1.to_d\n\n# good - not an actual float comparison\nx == Float::INFINITY\n\n# good\n(x - 0.1).abs < Float::EPSILON\n\n# good\ntolerance = 0.0001\n(x - 0.1).abs < tolerance\n\n# Or some other epsilon based type of comparison:\n# https://www.embeddeduse.com/2019/08/26/qt-compare-two-floats/\n----\n\n=== Exponential Notation [[exponential-notation]]\n\nWhen using exponential notation for numbers, prefer using the normalized scientific notation, which uses a mantissa between 1 (inclusive) and 10 (exclusive). Omit the exponent altogether if it is zero.\n\nThe goal is to avoid confusion between powers of ten and exponential notation, as one quickly reading `10e7` could think it's 10 to the power of 7 (one then 7 zeroes) when it's actually 10 to the power of 8 (one then 8 zeroes). If you want 10 to the power of 7, you should do `1e7`.\n\n|===\n| power notation | exponential notation | output\n\n| 10 ** 7        | 1e7                  | 10000000\n| 10 ** 6        | 1e6                  | 1000000\n| 10 ** 7        | 10e6                 | 10000000\n|===\n\nOne could favor the alternative engineering notation, in which the exponent must always be a multiple of 3 for easy conversion to the thousand / million / ... system.\n\n[source,ruby]\n----\n# bad\n10e6\n0.3e4\n11.7e5\n3.14e0\n\n# good\n1e7\n3e3\n1.17e6\n3.14\n----\n\nAlternative : engineering notation:\n\n[source,ruby]\n----\n# bad\n3.2e7\n0.1e5\n12e4\n\n# good\n1e6\n17e6\n0.98e9\n----\n\n== Strings\n\n=== String Interpolation [[string-interpolation]]\n\nPrefer string interpolation and string formatting to string concatenation:\n\n[source,ruby]\n----\n# bad\nemail_with_name = user.name + ' <' + user.email + '>'\n\n# good\nemail_with_name = \"#{user.name} <#{user.email}>\"\n\n# good\nemail_with_name = format('%s <%s>', user.name, user.email)\n----\n\n=== Consistent String Literals [[consistent-string-literals]]\n\nAdopt a consistent string literal quoting style.\nThere are two popular styles in the Ruby community, both of which are considered good - single quotes by default and double quotes by default.\n\nNOTE: The string literals in this guide are using single quotes by default.\n\n==== Single Quote [[consistent-string-literals-single-quote]]\n\nPrefer single-quoted strings when you don't need string interpolation or special symbols such as `\\t`, `\\n`, `'`, etc.\n\n[source,ruby]\n----\n# bad\nname = \"Bozhidar\"\n\nname = 'De\\'Andre'\n\n# good\nname = 'Bozhidar'\n\nname = \"De'Andre\"\n----\n\n==== Double Quote [[consistent-string-literals-double-quote]]\n\nPrefer double-quotes unless your string literal contains \" or escape characters you want to suppress.\n\n[source,ruby]\n----\n# bad\nname = 'Bozhidar'\n\nsarcasm = \"I \\\"like\\\" it.\"\n\n# good\nname = \"Bozhidar\"\n\nsarcasm = 'I \"like\" it.'\n----\n\n=== No Character Literals [[no-character-literals]]\n\nDon't use the character literal syntax `?x`.\nSince Ruby 1.9 it's basically redundant - `?x` would be interpreted as `'x'` (a string with a single character in it).\n\n[source,ruby]\n----\n# bad\nchar = ?c\n\n# good\nchar = 'c'\n----\n\n=== Curlies Interpolate [[curlies-interpolate]]\n\nDon't leave out `{}` around instance and global variables being interpolated into a string.\n\n[source,ruby]\n----\nclass Person\n  attr_reader :first_name, :last_name\n\n  def initialize(first_name, last_name)\n    @first_name = first_name\n    @last_name = last_name\n  end\n\n  # bad - valid, but awkward\n  def to_s\n    \"#@first_name #@last_name\"\n  end\n\n  # good\n  def to_s\n    \"#{@first_name} #{@last_name}\"\n  end\nend\n\n$global = 0\n# bad\nputs \"$global = #$global\"\n\n# good\nputs \"$global = #{$global}\"\n----\n\n=== No `to_s` [[no-to-s]]\n\nDon't use `Object#to_s` on interpolated objects.\nIt's called on them automatically.\n\n[source,ruby]\n----\n# bad\nmessage = \"This is the #{result.to_s}.\"\n\n# good\nmessage = \"This is the #{result}.\"\n----\n\n=== String Concatenation [[concat-strings]]\n\nAvoid using `pass:[String#+]` when you need to construct large data chunks.\nInstead, use `String#<<`.\nConcatenation mutates the string instance in-place and is always faster than `pass:[String#+]`, which creates a bunch of new string objects.\n\n[source,ruby]\n----\n# bad\nhtml = ''\nhtml += '<h1>Page title</h1>'\n\nparagraphs.each do |paragraph|\n  html += \"<p>#{paragraph}</p>\"\nend\n\n# good and also fast\nhtml = ''\nhtml << '<h1>Page title</h1>'\n\nparagraphs.each do |paragraph|\n  html << \"<p>#{paragraph}</p>\"\nend\n----\n\n=== Don't Abuse `gsub` [[dont-abuse-gsub]]\n\nDon't use `String#gsub` in scenarios in which you can use a faster and more specialized alternative.\n\n[source,ruby]\n----\nurl = 'http://example.com'\nstr = 'lisp-case-rules'\n\n# bad\nurl.gsub('http://', 'https://')\nstr.gsub('-', '_')\n\n# good\nurl.sub('http://', 'https://')\nstr.tr('-', '_')\n----\n\n=== `String#chars` [[string-chars]]\n\nPrefer the use of `String#chars` over `String#split` with empty string or regexp literal argument.\n\nNOTE: These cases have the same behavior since Ruby 2.0.\n\n[source,ruby]\n----\n# bad\nstring.split(//)\nstring.split('')\n\n# good\nstring.chars\n----\n\n=== `sprintf` [[sprintf]]\n\nPrefer the use of `sprintf` and its alias `format` over the fairly cryptic `String#%` method.\n\n[source,ruby]\n----\n# bad\n'%d %d' % [20, 10]\n# => '20 10'\n\n# good\nsprintf('%d %d', 20, 10)\n# => '20 10'\n\n# good\nsprintf('%<first>d %<second>d', first: 20, second: 10)\n# => '20 10'\n\nformat('%d %d', 20, 10)\n# => '20 10'\n\n# good\nformat('%<first>d %<second>d', first: 20, second: 10)\n# => '20 10'\n----\n\n=== Named Format Tokens [[named-format-tokens]]\n\nWhen using named format string tokens, favor `%<name>s` over `%{name}` because it encodes information about the type of the value.\n\n[source,ruby]\n----\n# bad\nformat('Hello, %{name}', name: 'John')\n\n# good\nformat('Hello, %<name>s', name: 'John')\n----\n\n=== Long Strings [[heredoc-long-strings]]\n\nBreak long strings into multiple lines but don't concatenate them with `+`.\nIf you want to add newlines, use heredoc. Otherwise use `\\`:\n\n[source,ruby]\n----\n# bad\n\"Lorem Ipsum is simply dummy text of the printing and typesetting industry. \" +\n\"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, \" +\n\"when an unknown printer took a galley of type and scrambled it to make a type specimen book.\"\n\n# good\n<<~LOREM\n  Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n  Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,\n  when an unknown printer took a galley of type and scrambled it to make a type specimen book.\nLOREM\n\n# good\n\"Lorem Ipsum is simply dummy text of the printing and typesetting industry. \"\\\n\"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, \"\\\n\"when an unknown printer took a galley of type and scrambled it to make a type specimen book.\"\n----\n\n== Heredocs\n\n=== Squiggly Heredocs [[squiggly-heredocs]]\n\nUse Ruby 2.3's squiggly heredocs for nicely indented multi-line strings.\n\n[source,ruby]\n----\n# bad - using Powerpack String#strip_margin\ncode = <<-RUBY.strip_margin('|')\n  |def test\n  |  some_method\n  |  other_method\n  |end\nRUBY\n\n# also bad\ncode = <<-RUBY\ndef test\n  some_method\n  other_method\nend\nRUBY\n\n# good\ncode = <<~RUBY\n  def test\n    some_method\n    other_method\n  end\nRUBY\n----\n\n=== Heredoc Delimiters [[heredoc-delimiters]]\n\nUse descriptive delimiters for heredocs.\nDelimiters add valuable information about the heredoc content, and as an added bonus some editors can highlight code within heredocs if the correct delimiter is used.\n\n[source,ruby]\n----\n# bad\ncode = <<~END\n  def foo\n    bar\n  end\nEND\n\n# good\ncode = <<~RUBY\n  def foo\n    bar\n  end\nRUBY\n\n# good\ncode = <<~SUMMARY\n  An imposing black structure provides a connection between the past and\n  the future in this enigmatic adaptation of a short story by revered\n  sci-fi author Arthur C. Clarke.\nSUMMARY\n----\n\n=== Heredoc Method Calls [[heredoc-method-calls]]\n\nPlace method calls with heredoc receivers on the first line of the heredoc definition.\nThe bad form has significant potential for error if a new line is added or removed.\n\n[source,ruby]\n----\n# bad\nquery = <<~SQL\n  select foo from bar\nSQL\n.strip_indent\n\n# good\nquery = <<~SQL.strip_indent\n  select foo from bar\nSQL\n----\n\n=== Heredoc Argument Closing Parentheses [[heredoc-argument-closing-parentheses]]\n\nPlace the closing parenthesis for method calls with heredoc arguments on the first line of the heredoc definition.\nThe bad form has potential for error if the new line before the closing parenthesis is removed.\n\n[source,ruby]\n----\n# bad\nfoo(<<~SQL\n  select foo from bar\nSQL\n)\n\n# good\nfoo(<<~SQL)\n  select foo from bar\nSQL\n----\n\n== Date & Time\n\n=== `Time.now` [[time-now]]\n\nPrefer `Time.now` over `Time.new` when retrieving the current system time.\n\n[source,ruby]\n----\n# bad\nTime.new\n\n# good\nTime.now\n----\n\n=== No `DateTime` [[no-datetime]]\n\nDon't use `DateTime` unless you need to account for historical calendar reform - and if you do, explicitly specify the `start` argument to clearly state your intentions.\n\n[source,ruby]\n----\n# bad - uses DateTime for current time\nDateTime.now\n\n# good - uses Time for current time\nTime.now\n\n# bad - uses DateTime for modern date\nDateTime.iso8601('2016-06-29')\n\n# good - uses Date for modern date\nDate.iso8601('2016-06-29')\n\n# good - uses DateTime with start argument for historical date\nDateTime.iso8601('1751-04-23', Date::ENGLAND)\n----\n\n== Regular Expressions\n\n[quote, Jamie Zawinski]\n____\nSome people, when confronted with a problem, think\n\"I know, I'll use regular expressions.\" Now they have two problems.\n____\n\n=== Plain Text Search [[no-regexp-for-plaintext]]\n\nDon't use regular expressions if you just need plain text search in string.\n\n[source,ruby]\n----\nfoo = 'I am an example string'\n\n# bad - using a regular expression is an overkill here\nfoo =~ /example/\n\n# good\nfoo['example']\n----\n\n=== Using Regular Expressions as String Indexes [[regexp-string-index]]\n\nFor simple constructions you can use regexp directly through string index.\n\n[source,ruby]\n----\nmatch = string[/regexp/]             # get content of matched regexp\nfirst_group = string[/text(grp)/, 1] # get content of captured group\nstring[/text (grp)/, 1] = 'replace'  # string => 'text replace'\n----\n\n=== Prefer Non-capturing Groups [[non-capturing-regexp]]\n\nUse non-capturing groups when you don't use the captured result.\n\n[source,ruby]\n----\n# bad\n/(first|second)/\n\n# good\n/(?:first|second)/\n----\n\n=== Do not mix named and numbered captures [[do-not-mix-named-and-numbered-captures]]\n\nDo not mix named captures and numbered captures in a Regexp literal.\nBecause numbered capture is ignored if they're mixed.\n\n[source,ruby]\n----\n# bad - There is no way to access `(BAR)` capturing.\nm = /(?<foo>FOO)(BAR)/.match('FOOBAR')\np m[:foo] # => \"FOO\"\np m[1]    # => \"FOO\"\np m[2]    # => nil   - not \"BAR\"\n\n# good - Both captures are accessible with names.\nm = /(?<foo>FOO)(?<bar>BAR)/.match('FOOBAR')\np m[:foo] # => \"FOO\"\np m[:bar] # => \"BAR\"\n\n# good - `(?:BAR)` is non-capturing grouping.\nm = /(?<foo>FOO)(?:BAR)/.match('FOOBAR')\np m[:foo] # => \"FOO\"\n\n# good - Both captures are accessible with numbers.\nm = /(FOO)(BAR)/.match('FOOBAR')\np m[1] # => \"FOO\"\np m[2] # => \"BAR\"\n----\n\n=== Refer named regexp captures by name [[refer-named-regexp-captures-by-name]]\n\nPrefer using names to refer named regexp captures instead of numbers.\n\n[source,ruby]\n----\n# bad\nm = /(?<foo>FOO)(?<bar>BAR)/.match('FOOBAR')\np m[1] # => \"FOO\"\np m[2] # => \"BAR\"\n\n# good\nm = /(?<foo>FOO)(?<bar>BAR)/.match('FOOBAR')\np m[:foo] # => \"FOO\"\np m[:bar] # => \"BAR\"\n----\n\n=== Avoid Perl-style Last Regular Expression Group Matchers [[no-perl-regexp-last-matchers]]\n\nDon't use the cryptic Perl-legacy variables denoting last regexp group matches (`$1`, `$2`, etc).\nUse `Regexp.last_match(n)` instead.\n\n[source,ruby]\n----\n/(regexp)/ =~ string\n...\n\n# bad\nprocess $1\n\n# good\nprocess Regexp.last_match(1)\n----\n\n=== Avoid Numbered Groups [[no-numbered-regexes]]\n\nAvoid using numbered groups as it can be hard to track what they contain.\nNamed groups can be used instead.\n\n[source,ruby]\n----\n# bad\n/(regexp)/ =~ string\n# some code\nprocess Regexp.last_match(1)\n\n# good\n/(?<meaningful_var>regexp)/ =~ string\n# some code\nprocess meaningful_var\n----\n\n=== Limit Escapes [[limit-escapes]]\n\nCharacter classes have only a few special characters you should care about: `^`, `-`, `\\`, `]`, so don't escape `.` or brackets in `[]`.\n\n=== Caret and Dollar Regexp [[caret-and-dollar-regexp]]\n\nBe careful with `^` and `$` as they match start/end of line, not string endings.\nIf you want to match the whole string use: `\\A` and `\\z` (not to be confused with `\\Z` which is the equivalent of `/\\n?\\z/`).\n\n[source,ruby]\n----\nstring = \"some injection\\nusername\"\nstring[/^username$/]   # matches\nstring[/\\Ausername\\z/] # doesn't match\n----\n\n=== Multi-line Regular Expressions [[multi-line-regexes]]\n\nUse `x` (free-spacing) modifier for multi-line regexps.\n\nNOTE: That's known as https://www.regular-expressions.info/freespacing.html[free-spacing mode]. In this mode leading and trailing whitespace is ignored.\n\n[source,ruby]\n----\n# bad\nregex = /start\\\n\\s\\\n(group)\\\n(?:alt1|alt2)\\\nend/\n\n# good\nregexp = /\n  start\n  \\s\n  (group)\n  (?:alt1|alt2)\n  end\n/x\n----\n\n=== Comment Complex Regular Expressions [[comment-regexes]]\n\nUse `x` modifier for complex regexps.\nThis makes them more readable and you can add some useful comments.\n\n[source,ruby]\n----\nregexp = /\n  start         # some text\n  \\s            # white space char\n  (group)       # first group\n  (?:alt1|alt2) # some alternation\n  end\n/x\n----\n\n=== Use `gsub` with a Block or a Hash for Complex Replacements [[gsub-blocks]]\n\nFor complex replacements `sub`/`gsub` can be used with a block or a hash.\n\n[source,ruby]\n----\nwords = 'foo bar'\nwords.sub(/f/, 'f' => 'F') # => 'Foo bar'\nwords.gsub(/\\w+/) { |word| word.capitalize } # => 'Foo Bar'\n----\n\n== Percent Literals\n\n=== `%q` shorthand [[percent-q-shorthand]]\n\nUse `%()` (it's a shorthand for `%Q`) for single-line strings which require both interpolation and embedded double-quotes.\nFor multi-line strings, prefer heredocs.\n\n[source,ruby]\n----\n# bad (no interpolation needed)\n%(<div class=\"text\">Some text</div>)\n# should be '<div class=\"text\">Some text</div>'\n\n# bad (no double-quotes)\n%(This is #{quality} style)\n# should be \"This is #{quality} style\"\n\n# bad (multiple lines)\n%(<div>\\n<span class=\"big\">#{exclamation}</span>\\n</div>)\n# should be a heredoc.\n\n# good (requires interpolation, has quotes, single line)\n%(<tr><td class=\"name\">#{name}</td>)\n----\n\n=== `%q` [[percent-q]]\n\nAvoid `%()` or the equivalent `%q()` unless you have a string with both `'` and `\"` in it.\nRegular string literals are more readable and should be preferred unless a lot of characters would have to be escaped in them.\n\n[source,ruby]\n----\n# bad\nname = %q(Bruce Wayne)\ntime = %q(8 o'clock)\nquestion = %q(\"What did you say?\")\n\n# good\nname = 'Bruce Wayne'\ntime = \"8 o'clock\"\nquestion = '\"What did you say?\"'\nquote = %q(<p class='quote'>\"What did you say?\"</p>)\n----\n\n=== `%r` [[percent-r]]\n\nUse `%r` only for regular expressions matching _at least_ one `/` character.\n\n[source,ruby]\n----\n# bad\n%r{\\s+}\n\n# good\n%r{^/(.*)$}\n%r{^/blog/2011/(.*)$}\n----\n\n=== `%x` [[percent-x]]\n\nAvoid the use of `%x` unless you're going to execute a command with backquotes in it (which is rather unlikely).\n\n[source,ruby]\n----\n# bad\ndate = %x(date)\n\n# good\ndate = `date`\necho = %x(echo `date`)\n----\n\n=== `%s` [[percent-s]]\n\nAvoid the use of `%s`.\nIt seems that the community has decided `:\"some string\"` is the preferred way to create a symbol with spaces in it.\n\n[source,ruby]\n----\n# bad\n%s(some symbol)\n\n# good\n:\"some symbol\"\n----\n\n=== Percent Literal Braces [[percent-literal-braces]]\n\nUse the braces that are the most appropriate for the various kinds of percent literals.\n\n * `()` for string literals (`%q`, `%Q`).\n * `[]` for array literals (`%w`, `%i`, `%W`, `%I`) as it is aligned with the standard array literals.\n * `{}` for regexp literals (`%r`) since parentheses often appear inside regular expressions. That's why a less common character with `{` is usually the best delimiter for `%r` literals.\n * `()` for all other literals (e.g. `%s`, `%x`)\n\n[source,ruby]\n----\n# bad\n%q{\"Test's king!\", John said.}\n\n# good\n%q(\"Test's king!\", John said.)\n\n# bad\n%w(one two three)\n%i(one two three)\n\n# good\n%w[one two three]\n%i[one two three]\n\n# bad\n%r((\\w+)-(\\d+))\n%r{\\w{1,2}\\d{2,5}}\n\n# good\n%r{(\\w+)-(\\d+)}\n%r|\\w{1,2}\\d{2,5}|\n----\n\n== Metaprogramming\n\n=== No Needless Metaprogramming [[no-needless-metaprogramming]]\n\nAvoid needless metaprogramming.\n\n[source,ruby]\n----\n# bad\nclass Person\n  %i[name age email].each do |attr|\n    define_method(attr) { instance_variable_get(\"@#{attr}\") }\n  end\nend\n\n# good\nclass Person\n  attr_reader :name, :age, :email\nend\n----\n\n=== No Monkey Patching [[no-monkey-patching]]\n\nDo not mess around in core classes when writing libraries (do not monkey-patch them).\n\n[source,ruby]\n----\n# bad\nclass String\n  def to_hierarchical_date\n    split('-').map(&:to_i)\n  end\nend\n\n# good - use refinements instead\nmodule DateParsing\n  refine String do\n    def to_hierarchical_date\n      split('-').map(&:to_i)\n    end\n  end\nend\n----\n\n=== Block `class_eval` [[block-class-eval]]\n\nThe block form of `class_eval` is preferable to the string-interpolated form.\n\n==== Supply Location [[class-eval-supply-location]]\n\nWhen you use the string-interpolated form, always supply `+__FILE__+` and `+__LINE__+`, so that your backtraces make sense:\n\n[source,ruby]\n----\nclass_eval 'def use_relative_model_naming?; true; end', __FILE__, __LINE__\n----\n\n==== `define_method` [[class-eval-define_method]]\n\n`define_method` is preferable to `class_eval { def ... }`\n\n=== `eval` Comment Docs [[eval-comment-docs]]\n\nWhen using `class_eval` (or other `eval`) with string interpolation, add a comment block showing its appearance if interpolated (a practice used in Rails code):\n\n[source,ruby]\n----\n# from activesupport/lib/active_support/core_ext/string/output_safety.rb\nUNSAFE_STRING_METHODS.each do |unsafe_method|\n  if 'String'.respond_to?(unsafe_method)\n    class_eval <<-EOT, __FILE__, __LINE__ + 1\n      def #{unsafe_method}(*params, &block)       # def capitalize(*params, &block)\n        to_str.#{unsafe_method}(*params, &block)  #   to_str.capitalize(*params, &block)\n      end                                         # end\n\n      def #{unsafe_method}!(*params)              # def capitalize!(*params)\n        @dirty = true                             #   @dirty = true\n        super                                     #   super\n      end                                         # end\n    EOT\n  end\nend\n----\n\n=== No `method_missing` [[no-method-missing]]\n\nAvoid using `method_missing` for metaprogramming because backtraces become messy, the behavior is not listed in `#methods`, and misspelled method calls might silently work, e.g. `nukes.luanch_state = false`.\nConsider using delegation, proxy, or `define_method` instead.\nIf you must use `method_missing`:\n\n * Be sure to https://thoughtbot.com/blog/always-define-respond-to-missing-when-overriding[also define `respond_to_missing?`]\n * Only catch methods with a well-defined prefix, such as `find_by_*`--make your code as assertive as possible.\n * Call `super` at the end of your statement\n * Delegate to assertive, non-magical methods:\n\n[source,ruby]\n----\n# bad\ndef method_missing(meth, *params, &block)\n  if /^find_by_(?<prop>.*)/ =~ meth\n    # ... lots of code to do a find_by\n  else\n    super\n  end\nend\n\n# good\ndef method_missing(meth, *params, &block)\n  if /^find_by_(?<prop>.*)/ =~ meth\n    find_by(prop, *params, &block)\n  else\n    super\n  end\nend\n\n# best of all, though, would be to define_method as each findable attribute is declared\n----\n\n=== Prefer `public_send` [[prefer-public-send]]\n\nPrefer `public_send` over `send` so as not to circumvent `private`/`protected` visibility.\n\n[source,ruby]\n----\n# We have an ActiveModel Organization that includes concern Activatable\nmodule Activatable\n  extend ActiveSupport::Concern\n\n  included do\n    before_create :create_token\n  end\n\n  private\n\n  def reset_token\n    # some code\n  end\n\n  def create_token\n    # some code\n  end\n\n  def activate!\n    # some code\n  end\nend\n\nclass Organization < ActiveRecord::Base\n  include Activatable\nend\n\nlinux_organization = Organization.find(...)\n\n# bad - violates privacy\nlinux_organization.send(:reset_token)\n# good - should throw an exception\nlinux_organization.public_send(:reset_token)\n----\n\n=== Prefer `+__send__+` [[prefer-__send__]]\n\nPrefer `+__send__+` over `send`, as `send` may overlap with existing methods.\n\n[source,ruby]\n----\nrequire 'socket'\n\nu1 = UDPSocket.new\nu1.bind('127.0.0.1', 4913)\nu2 = UDPSocket.new\nu2.connect('127.0.0.1', 4913)\n\n# bad - Won't send a message to the receiver object. Instead it will send a message via UDP socket.\nu2.send :sleep, 0\n# good - Will actually send a message to the receiver object.\nu2.__send__ ...\n----\n\n== API Documentation [[api-documentation]]\n\n=== YARD\n\nUse https://yardoc.org/[YARD] and its conventions for API documentation.\n\n=== RD (Block) Comments [[no-block-comments]]\n\nDon't use block comments.\nThey cannot be preceded by whitespace and are not as easy to spot as regular comments.\n\n[source,ruby]\n----\n# bad\n=begin\ncomment line\nanother comment line\n=end\n\n# good\n# comment line\n# another comment line\n----\n\n.From Perl's POD to RD\n****\nThis is not really a block comment syntax, but more of\nan attempt to emulate Perl's https://perldoc.perl.org/perlpod.html[POD] documentation system.\n\nThere's an https://github.com/uwabami/rdtool[rdtool] for Ruby that's pretty similar to POD.\nBasically `rdtool` scans a file for `=begin` and `=end` pairs, and extracts\nthe text between them all. This text is assumed to be documentation in\nhttps://github.com/uwabami/rdtool/blob/master/doc/rd-draft.rd[RD format].\nYou can read more about it\nhttps://ruby-doc.com/docs/ProgrammingRuby/html/rdtool.html[here].\n\nRD predated the rise of RDoc and YARD and was effectively obsoleted by them.footnote:[According to this https://en.wikipedia.org/wiki/Ruby_Document_format[Wikipedia article] the format used to be popular until the early 2000s when it was superseded by RDoc.]\n****\n\n== Gemfile and Gemspec\n\n=== No `RUBY_VERSION` in the gemspec [[no-ruby-version-in-the-gemspec]]\n\nThe gemspec should not contain `RUBY_VERSION` as a condition to switch dependencies.\n`RUBY_VERSION` is determined by `rake release`, so users may end up with wrong dependency.\n\n[source,ruby]\n----\n# bad\nGem::Specification.new do |s|\n  if RUBY_VERSION >= '2.5'\n    s.add_dependency 'gem_a'\n  else\n    s.add_dependency 'gem_b'\n  end\nend\n----\n\nFix by either:\n\n* Post-install messages.\n* Add both gems as dependency (if permissible).\n* If development dependencies, move to Gemfile.\n\n=== `add_dependency` vs `add_runtime_dependency` [[add_dependency_vs_add_runtime_dependency]]\n\nPrefer `add_dependency` over `add_runtime_dependency` because `add_runtime_dependency` is considered soft-deprecated\nand the Bundler team recommends `add_dependency`.\n\n[source,ruby]\n----\n# bad\nGem::Specification.new do |s|\n  s.add_runtime_dependency 'gem_a'\nend\n\n# good\nGem::Specification.new do |s|\n  s.add_dependency 'gem_a'\nend\n----\n\nSee https://github.com/rubygems/rubygems/issues/7799#issuecomment-2192720316 for details.\n\n== Misc\n\n=== No Flip-flops [[no-flip-flops]]\n\nAvoid the use of https://en.wikipedia.org/wiki/Flip-flop_(programming)[flip-flop operators].\n\n=== No non-`nil` Checks [[no-non-nil-checks]]\n\nDon't do explicit non-`nil` checks unless you're dealing with boolean values.\n\n[source,ruby]\n----\n# bad\ndo_something if !something.nil?\ndo_something if something != nil\n\n# good\ndo_something if something\n\n# good - dealing with a boolean\ndef value_set?\n  !@some_boolean.nil?\nend\n----\n\n=== Global Input/Output Streams [[global-stdout]]\n\nUse `$stdout/$stderr/$stdin` instead of `STDOUT/STDERR/STDIN`.\n`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.\n\n[source,ruby]\n----\n# bad\nSTDOUT.puts('hello')\n\nhash = { out: STDOUT, key: value }\n\ndef m(out = STDOUT)\n  out.puts('hello')\nend\n\n# good\n$stdout.puts('hello')\n\nhash = { out: $stdout, key: value }\n\ndef m(out = $stdout)\n  out.puts('hello')\nend\n----\n\nNOTE: The only valid use-case for the stream constants is obtaining references to the original streams (assuming you've redirected some of the global vars).\n\n=== Warn [[warn]]\n\nUse `warn` instead of `$stderr.puts`.\nApart 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`).\n\n[source,ruby]\n----\n# bad\n$stderr.puts 'This is a warning!'\n\n# good\nwarn 'This is a warning!'\n----\n\n=== `Array#join` [[array-join]]\n\nPrefer the use of `Array#join` over the fairly cryptic `Array#*` with a string argument.\n\n[source,ruby]\n----\n# bad\n%w[one two three] * ', '\n# => 'one, two, three'\n\n# good\n%w[one two three].join(', ')\n# => 'one, two, three'\n----\n\n=== Array Coercion [[array-coercion]]\n\nUse `Array()` instead of explicit `Array` check or `[*var]`, when dealing with a variable you want to treat as an Array, but you're not certain it's an array.\n\n[source,ruby]\n----\n# bad\npaths = [paths] unless paths.is_a?(Array)\npaths.each { |path| do_something(path) }\n\n# bad (always creates a new Array instance)\n[*paths].each { |path| do_something(path) }\n\n# good (and a bit more readable)\nArray(paths).each { |path| do_something(path) }\n----\n\n=== Ranges or `between` [[ranges-or-between]]\n\nUse ranges or `Comparable#between?` instead of complex comparison logic when possible.\n\n[source,ruby]\n----\n# bad\ndo_something if x >= 1000 && x <= 2000\n\n# good\ndo_something if (1000..2000).include?(x)\n\n# good\ndo_something if x.between?(1000, 2000)\n----\n\n=== Predicate Methods [[predicate-methods]]\n\nPrefer the use of predicate methods to explicit comparisons with `==`.\nNumeric comparisons are OK.\n\n[source,ruby]\n----\n# bad\nif x % 2 == 0\nend\n\nif x % 2 == 1\nend\n\nif x == nil\nend\n\n# good\nif x.even?\nend\n\nif x.odd?\nend\n\nif x.nil?\nend\n\nif x.zero?\nend\n\nif x == 0\nend\n----\n\n=== Bitwise Predicate Methods [[bitwise-predicate-methods]]\n\nPrefer bitwise predicate methods over direct comparison operations.\n\n[source,ruby]\n----\n# bad - checks any set bits\n(variable & flags).positive?\n\n# good\nvariable.anybits?(flags)\n\n# bad - checks all set bits\n(variable & flags) == flags\n\n# good\nvariable.allbits?(flags)\n\n# bad - checks no set bits\n(variable & flags).zero?\n(variable & flags) == 0\n\n# good\nvariable.nobits?(flags)\n----\n\n=== No Cryptic Perlisms [[no-cryptic-perlisms]]\n\nAvoid using Perl-style special variables (like `$:`, `$;`, etc).\nThey are quite cryptic and their use in anything but one-liner scripts is discouraged.\n\n[source,ruby]\n----\n# bad\n$:.unshift File.dirname(__FILE__)\n\n# good\n$LOAD_PATH.unshift File.dirname(__FILE__)\n----\n\nUse the human-friendly aliases provided by the `English` library if required.\n\n[source,ruby]\n----\n# bad\nprint $', $$\n\n# good\nrequire 'English'\nprint $POSTMATCH, $PID\n----\n\n=== Use `require_relative` whenever possible\n\nFor all your internal dependencies, you should use `require_relative`.\nUse of `require` should be reserved for external dependencies\n\n[source,ruby]\n----\n# bad\nrequire 'set'\nrequire 'my_gem/spec/helper'\nrequire 'my_gem/lib/something'\n\n# good\nrequire 'set'\nrequire_relative 'helper'\nrequire_relative '../lib/something'\n----\n\nThis 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`).\n\n=== Always Warn [[always-warn]]\n\nWrite `ruby -w` safe code.\n\n=== No Optional Hash Params [[no-optional-hash-params]]\n\nAvoid hashes as optional parameters.\nDoes the method do too much? (Object initializers are exceptions for this rule).\n\n[source,ruby]\n----\n# bad\ndef send_email(subject, opts = {})\n  to = opts[:to]\n  cc = opts[:cc]\n  # ...\nend\n\n# good\ndef send_email(subject, to:, cc: nil)\n  # ...\nend\n----\n\n=== Instance Vars [[instance-vars]]\n\nUse module instance variables instead of global variables.\n\n[source,ruby]\n----\n# bad\n$foo_bar = 1\n\n# good\nmodule Foo\n  class << self\n    attr_accessor :bar\n  end\nend\n\nFoo.bar = 1\n----\n\n=== `OptionParser` [[optionparser]]\n\nUse `OptionParser` for parsing complex command line options and `ruby -s` for trivial command line options.\n\n=== No Param Mutations [[no-param-mutations]]\n\nDo not mutate parameters unless that is the purpose of the method.\n\n[source,ruby]\n----\n# bad\ndef clean(users)\n  users.reject!(&:disabled?)\n  users\nend\n\n# good\ndef clean(users)\n  users.reject(&:disabled?)\nend\n----\n\n=== Three is the Number Thou Shalt Count [[three-is-the-number-thou-shalt-count]]\n\nAvoid more than three levels of block nesting.\n\n[source,ruby]\n----\n# bad\ndef process(items)\n  items.each do |item|\n    item.widgets.each do |widget|\n      widget.parts.each do |part|\n        part.update!\n      end\n    end\n  end\nend\n\n# good\ndef process(items)\n  items.each do |item|\n    process_widgets(item.widgets)\n  end\nend\n\ndef process_widgets(widgets)\n  widgets.each do |widget|\n    widget.parts.each(&:update!)\n  end\nend\n----\n\n=== Functional Code [[functional-code]]\n\nCode in a functional way, avoiding mutation when that makes sense.\n\n[source,ruby]\n----\na = []; [1, 2, 3].each { |i| a << i * 2 }   # bad\na = [1, 2, 3].map { |i| i * 2 }             # good\n\na = {}; [1, 2, 3].each { |i| a[i] = i * 17 }                # bad\na = [1, 2, 3].reduce({}) { |h, i| h[i] = i * 17; h }        # good\na = [1, 2, 3].each_with_object({}) { |i, h| h[i] = i * 17 } # good\n----\n\n=== No explicit `.rb` to `require` [[no-explicit-rb-to-require]]\n\nOmit the `.rb` extension for filename passed to `require` and `require_relative`.\n\nNOTE: If the extension is omitted, Ruby tries adding '.rb', '.so', and so on to the name\nuntil found. If the file named cannot be found, a `LoadError` will be raised.\nThere is an edge case where `foo.so` file is loaded instead of a `LoadError`\nif `foo.so` file exists when `require 'foo.rb'` will be changed to `require 'foo'`,\nbut that seems harmless.\n\n[source,ruby]\n----\n# bad\nrequire 'foo.rb'\nrequire_relative '../foo.rb'\n\n# good\nrequire 'foo'\nrequire 'foo.so'\nrequire_relative '../foo'\nrequire_relative '../foo.so'\n----\n\n=== Avoid `tap`\n\nThe method `tap` can be helpful for debugging purposes but should not be left in production code.\n[source,ruby]\n----\n# bad\nConfig.new(hash, path).tap do |config|\n  config.check if check\nend\n\n# good\nconfig = Config.new(hash, path)\nconfig.check if check\nconfig\n----\n\nThis is simpler and more efficient.\n\n== Tools\n\nHere are some tools to help you automatically check Ruby code against this guide.\n\n=== RuboCop\n\nhttps://github.com/rubocop/rubocop[RuboCop] is a Ruby static code analyzer and formatter, based on this style guide.\nRuboCop already covers a significant portion of the guide and has https://docs.rubocop.org/rubocop/integration_with_other_tools.html[plugins] for most popular Ruby editors and IDEs.\n\nTIP: RuboCop's cops (code checks) have links to the guidelines that they are based on, as part of their metadata.\n\n=== RubyMine\n\nhttps://www.jetbrains.com/ruby/[RubyMine]'s code inspections are https://confluence.jetbrains.com/display/RUBYDEV/RubyMine+Inspections[partially based] on this guide.\n\n== History\n\nThis guide started its life in 2011 as an internal company Ruby coding guidelines (written by https://github.com/bbatsov[Bozhidar Batsov]).\nBozhidar had always been bothered as a Ruby developer about one thing - Python developers had a great programming style reference (https://www.python.org/dev/peps/pep-0008/[PEP-8]) and Rubyists never got an official guide, documenting Ruby coding style and best practices.\nBozhidar firmly believed that style matters.\nHe also believed that a great hacker community, such as Ruby has, should be quite capable of producing this coveted document.\nThe rest is history...\n\nAt some point Bozhidar decided that the work he was doing might be interesting to members of the Ruby community in general and that the world had little need for another internal company guideline.\nBut the world could certainly benefit from a community-driven and community-sanctioned set of practices, idioms and style prescriptions for Ruby programming.\n\nBozhidar served as the guide's only editor for a few years, before a team of editors was formed once the project transitioned to RuboCop HQ.\n\nSince the inception of the guide we've received a lot of feedback from members of the exceptional Ruby community around the world.\nThanks for all the suggestions and the support! Together we can make a resource beneficial to each and every Ruby developer out there.\n\n== Sources of Inspiration\n\nMany people, books, presentations, articles and other style guides influenced the community Ruby style guide. Here are some of them:\n\n* https://en.wikipedia.org/wiki/The_Elements_of_Style[\"The Elements of Style\"]\n* https://en.wikipedia.org/wiki/The_Elements_of_Programming_Style[\"The Elements of Programming Style\"]\n* https://www.python.org/dev/peps/pep-0008/[The Python Style Guide (PEP-8)]\n* https://pragprog.com/book/ruby4/programming-ruby-1-9-2-0[\"Programming Ruby\"]\n* https://www.amazon.com/Ruby-Programming-Language-David-Flanagan/dp/0596516177[\"The Ruby Programming Language\"]\n\n== Contributing\n\nThe guide is still a work in progress - some guidelines are lacking examples, some guidelines don't have examples that illustrate them clearly enough.\nImproving such guidelines is a great (and simple) way to help the Ruby community!\n\nIn due time these issues will (hopefully) be addressed - just keep them in mind for now.\n\nNothing written in this guide is set in stone.\nIt's our desire to work together with everyone interested in Ruby coding style, so that we could ultimately create a resource that will be beneficial to the entire Ruby community.\n\nFeel free to open tickets or send pull requests with improvements.\nThanks in advance for your help!\n\nYou can also support the project (and RuboCop) with financial contributions via one of the following platforms:\n\n* https://github.com/sponsors/bbatsov[GitHub Sponsors]\n* https://ko-fi.com/bbatsov[ko-fi]\n* https://www.patreon.com/bbatsov[Patreon]\n* https://www.paypal.me/bbatsov[PayPal]\n\n=== How to Contribute?\n\nIt's easy, just follow the contribution guidelines below:\n\n* https://help.github.com/articles/fork-a-repo[Fork] https://github.com/rubocop/ruby-style-guide[rubocop/ruby-style-guide] on GitHub\n* Make your feature addition or bug fix in a feature branch.\n* Include a https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[good description] of your changes\n* Push your feature branch to GitHub\n* Send a https://help.github.com/articles/using-pull-requests[Pull Request]\n\n== Colophon\n\nThis guide is written in https://asciidoc.org/[AsciiDoc] and is published as HTML using https://asciidoctor.org/[AsciiDoctor].\nThe HTML version of the guide is hosted on GitHub Pages.\n\nOriginally the guide was written in Markdown, but was converted to AsciiDoc in 2019.\n\n== License\n\nimage:https://i.creativecommons.org/l/by/3.0/88x31.png[Creative Commons License] This work is licensed under a https://creativecommons.org/licenses/by/3.0/deed.en_US[Creative Commons Attribution 3.0 Unported License]\n\n== Spread the Word\n\nA community-driven style guide is of little use to a community that doesn't know about its existence.\nTweet about the guide, share it with your friends and colleagues.\nEvery comment, suggestion or opinion we get makes the guide just a little bit better.\nAnd we want to have the best possible guide, don't we?\n"
  },
  {
    "path": "codespell.txt",
    "content": "revered\nrouge\nsting\n"
  }
]