{"id":13393127,"url":"https://github.com/airbnb/ruby","last_synced_at":"2025-09-04T17:13:21.771Z","repository":{"id":6721376,"uuid":"7967167","full_name":"airbnb/ruby","owner":"airbnb","description":"Ruby Style Guide","archived":false,"fork":false,"pushed_at":"2025-08-22T04:02:42.000Z","size":396,"stargazers_count":3870,"open_issues_count":15,"forks_count":759,"subscribers_count":279,"default_branch":"main","last_synced_at":"2025-08-29T06:33:21.661Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/airbnb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2013-02-01T21:49:13.000Z","updated_at":"2025-08-26T19:56:56.000Z","dependencies_parsed_at":"2024-02-04T18:36:15.441Z","dependency_job_id":"78032b48-99a9-40fa-ad9f-7e1148ceabbc","html_url":"https://github.com/airbnb/ruby","commit_stats":{"total_commits":242,"total_committers":56,"mean_commits":4.321428571428571,"dds":0.884297520661157,"last_synced_commit":"53d10946c67453dec7309dce75727c3b8283e405"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"purl":"pkg:github/airbnb/ruby","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/airbnb%2Fruby","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/airbnb%2Fruby/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/airbnb%2Fruby/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/airbnb%2Fruby/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/airbnb","download_url":"https://codeload.github.com/airbnb/ruby/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/airbnb%2Fruby/sbom","scorecard":{"id":173420,"data":{"date":"2025-08-11","repo":{"name":"github.com/airbnb/ruby","commit":"09a4a0788dbaefee8776c15291b5d6fd33ad9d82"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":7,"checks":[{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Code-Review","score":10,"reason":"all changesets reviewed","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Token-Permissions","score":10,"reason":"GitHub workflow tokens follow principle of least privilege","details":["Info: topLevel 'contents' permission set to 'read': .github/workflows/rspec_rubocop.yml:9","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Pinned-Dependencies","score":8,"reason":"dependency not pinned by hash detected -- score normalized to 8","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/rspec_rubocop.yml:30: update your workflow using https://app.stepsecurity.io/secureworkflow/airbnb/ruby/rspec_rubocop.yml/main?enable=pin","Info:   0 out of   1 GitHub-owned GitHubAction dependencies pinned","Info:   1 out of   1 third-party GitHubAction dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE.md:0","Info: FSF or OSI recognized license: MIT License: LICENSE.md:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Security-Policy","score":9,"reason":"security policy file detected","details":["Info: security policy file detected: github.com/airbnb/.github/SECURITY.md:1","Info: Found linked content: github.com/airbnb/.github/SECURITY.md:1","Warn: One or no descriptive hints of disclosure, vulnerability, and/or timelines in security policy","Info: Found text in security policy: github.com/airbnb/.github/SECURITY.md:1"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 30 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}}]},"last_synced_at":"2025-08-16T17:08:12.366Z","repository_id":6721376,"created_at":"2025-08-16T17:08:12.366Z","updated_at":"2025-08-16T17:08:12.366Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273641904,"owners_count":25142252,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-04T02:00:08.968Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T17:00:43.758Z","updated_at":"2025-09-04T17:13:21.749Z","avatar_url":"https://github.com/airbnb.png","language":"Ruby","readme":"# Ruby Style Guide\n\nThis is Airbnb's Ruby Style Guide.\n\nIt was inspired by [GitHub's guide](https://web.archive.org/web/20160410033955/https://github.com/styleguide/ruby) and [RuboCop's guide][rubocop-guide].\n\nAirbnb also maintains a [JavaScript Style Guide][airbnb-javascript].\n\n## Table of Contents\n  1. [Whitespace](#whitespace)\n      1. [Indentation](#indentation)\n      1. [Inline](#inline)\n      1. [Newlines](#newlines)\n  1. [Line Length](#line-length)\n  1. [Commenting](#commenting)\n      1. [File/class-level comments](#fileclass-level-comments)\n      1. [Function comments](#function-comments)\n      1. [Block and inline comments](#block-and-inline-comments)\n      1. [Punctuation, spelling, and grammar](#punctuation-spelling-and-grammar)\n      1. [TODO comments](#todo-comments)\n      1. [Commented-out code](#commented-out-code)\n  1. [Methods](#methods)\n      1. [Method definitions](#method-definitions)\n      1. [Method calls](#method-calls)\n  1. [Conditional Expressions](#conditional-expressions)\n      1. [Conditional keywords](#conditional-keywords)\n      1. [Ternary operator](#ternary-operator)\n  1. [Syntax](#syntax)\n  1. [Naming](#naming)\n  1. [Classes](#classes)\n  1. [Exceptions](#exceptions)\n  1. [Collections](#collections)\n  1. [Strings](#strings)\n  1. [Regular Expressions](#regular-expressions)\n  1. [Percent Literals](#percent-literals)\n  1. [Rails](#rails)\n      1. [Scopes](#scopes)\n  1. [Be Consistent](#be-consistent)\n  1. [Translation](#translation)\n\n## Whitespace\n\n### Indentation\n\n* \u003ca name=\"default-indentation\"\u003e\u003c/a\u003eUse soft-tabs with a\n    two-space indent.\u003csup\u003e[[link](#default-indentation)]\u003c/sup\u003e\n\n* \u003ca name=\"indent-when-as-case\"\u003e\u003c/a\u003eIndent `when` as deep as `case`.\n    \u003csup\u003e[[link](#indent-when-as-case)]\u003c/sup\u003e\n\n    ```ruby\n    case\n    when song.name == 'Misty'\n      puts 'Not again!'\n    when song.duration \u003e 120\n      puts 'Too long!'\n    when Time.now.hour \u003e 21\n      puts \"It's too late\"\n    else\n      song.play\n    end\n\n    kind = 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    ```\n\n* \u003ca name=\"align-function-params\"\u003e\u003c/a\u003eAlign function parameters either all on\n    the same line or one per line.\u003csup\u003e[[link](#align-function-params)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    def self.create_translation(phrase_id, phrase_key, target_locale,\n                                value, user_id, do_xss_check, allow_verification)\n      ...\n    end\n\n    # good\n    def self.create_translation(phrase_id,\n                                phrase_key,\n                                target_locale,\n                                value,\n                                user_id,\n                                do_xss_check,\n                                allow_verification)\n      ...\n    end\n\n    # good\n    def self.create_translation(\n      phrase_id,\n      phrase_key,\n      target_locale,\n      value,\n      user_id,\n      do_xss_check,\n      allow_verification\n    )\n      ...\n    end\n    ```\n\n* \u003ca name=\"indent-multi-line-bool\"\u003e\u003c/a\u003eIndent succeeding lines in multi-line\n    boolean expressions.\u003csup\u003e[[link](#indent-multi-line-bool)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    def is_eligible?(user)\n      Trebuchet.current.launch?(ProgramEligibilityHelper::PROGRAM_TREBUCHET_FLAG) \u0026\u0026\n      is_in_program?(user) \u0026\u0026\n      program_not_expired\n    end\n\n    # good\n    def is_eligible?(user)\n      Trebuchet.current.launch?(ProgramEligibilityHelper::PROGRAM_TREBUCHET_FLAG) \u0026\u0026\n        is_in_program?(user) \u0026\u0026\n        program_not_expired\n    end\n    ```\n\n### Inline\n\n* \u003ca name=\"trailing-whitespace\"\u003e\u003c/a\u003eNever leave trailing whitespace.\n    \u003csup\u003e[[link](#trailing-whitespace)]\u003c/sup\u003e\n\n* \u003ca name=\"space-before-comments\"\u003e\u003c/a\u003eWhen making inline comments, include a\n    space between the end of the code and the start of your comment.\n    \u003csup\u003e[[link](#space-before-comments)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    result = func(a, b)# we might want to change b to c\n\n    # good\n    result = func(a, b) # we might want to change b to c\n    ```\n\n* \u003ca name=\"spaces-operators\"\u003e\u003c/a\u003eUse spaces around operators; after commas,\n    colons, and semicolons; and around `{` and before `}`.\n    \u003csup\u003e[[link](#spaces-operators)]\u003c/sup\u003e\n\n    ```ruby\n    sum = 1 + 2\n    a, b = 1, 2\n    1 \u003e 2 ? true : false; puts 'Hi'\n    [1, 2, 3].each { |e| puts e }\n    ```\n\n* \u003ca name=\"no-space-before-commas\"\u003e\u003c/a\u003eNever include a space before a comma.\n    \u003csup\u003e[[link](#no-space-before-commas)]\u003c/sup\u003e\n\n    ```ruby\n    result = func(a, b)\n    ```\n\n* \u003ca name=\"spaces-block-params\"\u003e\u003c/a\u003eDo not include space inside block\n    parameter pipes. Include one space between parameters in a block.\n    Include one space outside block parameter pipes.\n    \u003csup\u003e[[link](#spaces-block-params)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    {}.each { | x,  y |puts x }\n\n    # good\n    {}.each { |x, y| puts x }\n    ```\n\n* \u003ca name=\"no-space-after-!\"\u003e\u003c/a\u003eDo not leave space between `!` and its\n    argument.\u003csup\u003e[[link](#no-space-after-!)]\u003c/sup\u003e\n\n    ```ruby\n    !something\n    ```\n\n* \u003ca name=\"no-spaces-braces\"\u003e\u003c/a\u003eNo spaces after `(`, `[` or before `]`, `)`.\n    \u003csup\u003e[[link](#no-spaces-braces)]\u003c/sup\u003e\n\n    ```ruby\n    some(arg).other\n    [1, 2, 3].length\n    ```\n\n* \u003ca name=\"no-spaces-string-interpolation\"\u003e\u003c/a\u003eOmit whitespace when doing\n    string interpolation.\u003csup\u003e[[link](#no-spaces-string-interpolation)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    var = \"This #{ foobar } is interpolated.\"\n\n    # good\n    var = \"This #{foobar} is interpolated.\"\n    ```\n\n* \u003ca name=\"no-spaces-range-literals\"\u003e\u003c/a\u003eDon't use extra whitespace in range\n    literals.\u003csup\u003e[[link](#no-spaces-range-literals)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    (0 ... coll).each do |item|\n\n    # good\n    (0...coll).each do |item|\n    ```\n\n### Newlines\n\n* \u003ca name=\"multiline-if-newline\"\u003e\u003c/a\u003eAdd a new line after `if` conditions spanning\n    multiple lines to help differentiate between the conditions and the body.\n    \u003csup\u003e[[link](#multiline-if-newline)]\u003c/sup\u003e\n\n    ```ruby\n    if @reservation_alteration.checkin == @reservation.start_date \u0026\u0026\n       @reservation_alteration.checkout == (@reservation.start_date + @reservation.nights)\n\n      redirect_to_alteration @reservation_alteration\n    end\n    ```\n\n* \u003ca name=\"newline-after-conditional\"\u003e\u003c/a\u003eAdd a new line after conditionals,\n    blocks, case statements, etc.\u003csup\u003e[[link](#newline-after-conditional)]\u003c/sup\u003e\n\n    ```ruby\n    if robot.is_awesome?\n      send_robot_present\n    end\n\n    robot.add_trait(:human_like_intelligence)\n    ```\n\n* \u003ca name=\"newline-different-indent\"\u003e\u003c/a\u003eDon’t include newlines between areas\n    of different indentation (such as around class or module bodies).\n    \u003csup\u003e[[link](#newline-different-indent)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    class Foo\n\n      def bar\n        # body omitted\n      end\n\n    end\n\n    # good\n    class Foo\n      def bar\n        # body omitted\n      end\n    end\n    ```\n\n* \u003ca name=\"newline-between-methods\"\u003e\u003c/a\u003eInclude one, but no more than one, new\n    line between methods.\u003csup\u003e[[link](#newline-between-methods)]\u003c/sup\u003e\n\n    ```ruby\n    def a\n    end\n\n    def b\n    end\n    ```\n\n* \u003ca name=\"method-def-empty-lines\"\u003e\u003c/a\u003eUse a single empty line to break between\n    statements to break up methods into logical paragraphs internally.\n    \u003csup\u003e[[link](#method-def-empty-lines)]\u003c/sup\u003e\n\n    ```ruby\n    def transformorize_car\n      car = manufacture(options)\n      t = transformer(robot, disguise)\n\n      car.after_market_mod!\n      t.transform(car)\n      car.assign_cool_name!\n\n      fleet.add(car)\n      car\n    end\n    ```\n\n* \u003ca name=\"trailing-newline\"\u003e\u003c/a\u003eEnd each file with a newline. Don't include\n    multiple newlines at the end of a file.\n    \u003csup\u003e[[link](#trailing-newline)]\u003c/sup\u003e\n\n## Line Length\n\n* Keep each line of code to a readable length. Unless\n  you have a reason not to, keep lines to fewer than 100 characters.\n  ([rationale](./rationales.md#line-length))\u003csup\u003e\n  [[link](#line-length)]\u003c/sup\u003e\n\n## Commenting\n\n\u003e Though a pain to write, comments are absolutely vital to keeping our code\n\u003e readable. The following rules describe what you should comment and where. But\n\u003e remember: while comments are very important, the best code is\n\u003e self-documenting. Giving sensible names to types and variables is much better\n\u003e than using obscure names that you must then explain through comments.\n\n\u003e When writing your comments, write for your audience: the next contributor who\n\u003e will need to understand your code. Be generous — the next one may be you!\n\n\u0026mdash;[Google C++ Style Guide][google-c++]\n\nPortions of this section borrow heavily from the Google\n[C++][google-c++-comments] and [Python][google-python-comments] style guides.\n\n### File/class-level comments\n\nEvery class definition should have an accompanying comment that describes what\nit is for and how it should be used.\n\nA file that contains zero classes or more than one class should have a comment\nat the top describing its contents.\n\n```ruby\n# Automatic conversion of one locale to another where it is possible, like\n# American to British English.\nmodule Translation\n  # Class for converting between text between similar locales.\n  # Right now only conversion between American English -\u003e British, Canadian,\n  # Australian, New Zealand variations is provided.\n  class PrimAndProper\n    def initialize\n      @converters = { :en =\u003e { :\"en-AU\" =\u003e AmericanToAustralian.new,\n                               :\"en-CA\" =\u003e AmericanToCanadian.new,\n                               :\"en-GB\" =\u003e AmericanToBritish.new,\n                               :\"en-NZ\" =\u003e AmericanToKiwi.new,\n                             } }\n    end\n\n  ...\n\n  # Applies transforms to American English that are common to\n  # variants of all other English colonies.\n  class AmericanToColonial\n    ...\n  end\n\n  # Converts American to British English.\n  # In addition to general Colonial English variations, changes \"apartment\"\n  # to \"flat\".\n  class AmericanToBritish \u003c AmericanToColonial\n    ...\n  end\n```\n\nAll files, including data and config files, should have file-level comments.\n\n```ruby\n# List of American-to-British spelling variants.\n#\n# This list is made with\n# lib/tasks/list_american_to_british_spelling_variants.rake.\n#\n# It contains words with general spelling variation patterns:\n#   [trave]led/lled, [real]ize/ise, [flav]or/our, [cent]er/re, plus\n# and these extras:\n#   learned/learnt, practices/practises, airplane/aeroplane, ...\n\nsectarianizes: sectarianises\nneutralization: neutralisation\n...\n```\n\n### Function comments\n\nEvery function declaration should have comments immediately preceding it that\ndescribe what the function does and how to use it. These comments should be\ndescriptive (\"Opens the file\") rather than imperative (\"Open the file\"); the\ncomment describes the function, it does not tell the function what to do. In\ngeneral, these comments do not describe how the function performs its task.\nInstead, that should be left to comments interspersed in the function's code.\n\nEvery function should mention what the inputs and outputs are, unless it meets\nall of the following criteria:\n\n* not externally visible\n* very short\n* obvious\n\nYou may use whatever format you wish. In Ruby, two popular function\ndocumentation schemes are [TomDoc](http://tomdoc.org/) and\n[YARD](https://rubydoc.info/docs/yard/file/docs/GettingStarted.md). You can also\njust write things out concisely:\n\n```ruby\n# Returns the fallback locales for the_locale.\n# If opts[:exclude_default] is set, the default locale, which is otherwise\n# always the last one in the returned list, will be excluded.\n#\n# For example:\n#   fallbacks_for(:\"pt-BR\")\n#     =\u003e [:\"pt-BR\", :pt, :en]\n#   fallbacks_for(:\"pt-BR\", :exclude_default =\u003e true)\n#     =\u003e [:\"pt-BR\", :pt]\ndef fallbacks_for(the_locale, opts = {})\n  ...\nend\n```\n\n### Block and inline comments\n\nThe final place to have comments is in tricky parts of the code. If you're\ngoing to have to explain it at the next code review, you should comment it now.\nComplicated operations get a few lines of comments before the operations\ncommence. Non-obvious ones get comments at the end of the line.\n\n```ruby\ndef fallbacks_for(the_locale, opts = {})\n  # dup() to produce an array that we can mutate.\n  ret = @fallbacks[the_locale].dup\n\n  # We make two assumptions here:\n  # 1) There is only one default locale (that is, it has no less-specific\n  #    children).\n  # 2) The default locale is just a language. (Like :en, and not :\"en-US\".)\n  if opts[:exclude_default] \u0026\u0026\n      ret.last == default_locale \u0026\u0026\n      ret.last != language_from_locale(the_locale)\n    ret.pop\n  end\n\n  ret\nend\n```\n\nOn the other hand, never describe the code. Assume the person reading the code\nknows the language (though not what you're trying to do) better than you do.\n\n\u003ca name=\"no-block-comments\"\u003e\u003c/a\u003eRelated: do not use block comments. They cannot\n  be preceded by whitespace and are not as easy to spot as regular comments.\n  \u003csup\u003e[[link](#no-block-comments)]\u003c/sup\u003e\n\n  ```ruby\n  # bad\n  =begin\n  comment line\n  another comment line\n  =end\n\n  # good\n  # comment line\n  # another comment line\n  ```\n\n### Punctuation, spelling and grammar\n\nPay attention to punctuation, spelling, and grammar; it is easier to read\nwell-written comments than badly written ones.\n\nComments should be as readable as narrative text, with proper capitalization\nand punctuation. In many cases, complete sentences are more readable than\nsentence fragments. Shorter comments, such as comments at the end of a line of\ncode, can sometimes be less formal, but you should be consistent with your\nstyle.\n\nAlthough it can be frustrating to have a code reviewer point out that you are\nusing a comma when you should be using a semicolon, it is very important that\nsource code maintain a high level of clarity and readability. Proper\npunctuation, spelling, and grammar help with that goal.\n\n### TODO comments\n\nUse TODO comments for code that is temporary, a short-term solution, or\ngood-enough but not perfect.\n\nTODOs should include the string TODO in all caps, followed by the full name\nof the person who can best provide context about the problem referenced by the\nTODO, in parentheses. A colon is optional. A comment explaining what there is\nto do is required. The main purpose is to have a consistent TODO format that\ncan be searched to find the person who can provide more details upon request.\nA TODO is not a commitment that the person referenced will fix the problem.\nThus when you create a TODO, it is almost always your name that is given.\n\n```ruby\n  # bad\n  # TODO(RS): Use proper namespacing for this constant.\n\n  # bad\n  # TODO(drumm3rz4lyfe): Use proper namespacing for this constant.\n\n  # good\n  # TODO(Ringo Starr): Use proper namespacing for this constant.\n```\n\n### Commented-out code\n\n* \u003ca name=\"commented-code\"\u003e\u003c/a\u003eNever leave commented-out code in our codebase.\n    \u003csup\u003e[[link](#commented-code)]\u003c/sup\u003e\n\n## Methods\n\n### Method definitions\n\n* \u003ca name=\"method-def-parens\"\u003e\u003c/a\u003eUse `def` with parentheses when there are\n    parameters. Omit the parentheses when the method doesn't accept any\n    parameters.\u003csup\u003e[[link](#method-def-parens)]\u003c/sup\u003e\n\n     ```ruby\n     def some_method\n       # body omitted\n     end\n\n     def some_method_with_parameters(arg1, arg2)\n       # body omitted\n     end\n     ```\n\n* \u003ca name=\"no-default-args\"\u003e\u003c/a\u003eDo not use default positional arguments.\n    Use keyword arguments (if available - in Ruby 2.0 or later) or an options\n    hash instead.\u003csup\u003e[[link](#no-default-args)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    def obliterate(things, gently = true, except = [], at = Time.now)\n      ...\n    end\n\n    # good\n    def obliterate(things, gently: true, except: [], at: Time.now)\n      ...\n    end\n\n    # good\n    def obliterate(things, options = {})\n      options = {\n        :gently =\u003e true, # obliterate with soft-delete\n        :except =\u003e [], # skip obliterating these things\n        :at =\u003e Time.now, # don't obliterate them until later\n      }.merge(options)\n\n      ...\n    end\n    ```\n\n* \u003ca name=\"no-single-line-methods\"\u003e\u003c/a\u003eAvoid single-line methods. Although\n    they are somewhat popular in the wild, there are a few peculiarities about\n    their definition syntax that make their use undesirable.\n    \u003csup\u003e[[link](#no-single-line-methods)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    def too_much; something; something_else; end\n\n    # good\n    def some_method\n      # body\n    end\n    ```\n\n### Method calls\n\n**Use parentheses** for a method call:\n\n* \u003ca name=\"returns-val-parens\"\u003e\u003c/a\u003eIf the method returns a value.\n    \u003csup\u003e[[link](#returns-val-parens)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    @current_user = User.find_by_id 1964192\n\n    # good\n    @current_user = User.find_by_id(1964192)\n    ```\n\n* \u003ca name=\"first-arg-parens\"\u003e\u003c/a\u003eIf the first argument to the method uses\n    parentheses.\u003csup\u003e[[link](#first-arg-parens)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    put! (x + y) % len, value\n\n    # good\n    put!((x + y) % len, value)\n    ```\n\n* \u003ca name=\"space-method-call\"\u003e\u003c/a\u003eNever put a space between a method name and\n    the opening parenthesis.\u003csup\u003e[[link](#space-method-call)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    f (3 + 2) + 1\n\n    # good\n    f(3 + 2) + 1\n    ```\n\n* \u003ca name=\"no-args-parens\"\u003e\u003c/a\u003e**Omit parentheses** for a method call if the\n    method accepts no arguments.\u003csup\u003e[[link](#no-args-parens)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    nil?()\n\n    # good\n    nil?\n    ```\n\n* \u003ca name=\"no-return-parens\"\u003e\u003c/a\u003eIf the method doesn't return a value (or we\n    don't care about the return), parentheses are optional. (Especially if the\n    arguments overflow to multiple lines, parentheses may add readability.)\n    \u003csup\u003e[[link](#no-return-parens)]\u003c/sup\u003e\n\n    ```ruby\n    # okay\n    render(:partial =\u003e 'foo')\n\n    # okay\n    render :partial =\u003e 'foo'\n    ```\n\nIn either case:\n\n* \u003ca name=\"options-no-braces\"\u003e\u003c/a\u003eIf a method accepts an options hash as the\n    last argument, do not use `{` `}` during invocation.\n    \u003csup\u003e[[link](#options-no-braces)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    get '/v1/reservations', { :id =\u003e 54875 }\n\n    # good\n    get '/v1/reservations', :id =\u003e 54875\n    ```\n\n## Conditional Expressions\n\n### Conditional keywords\n\n* \u003ca name=\"multiline-if-then\"\u003e\u003c/a\u003eNever use `then` for multi-line `if/unless`.\n    \u003csup\u003e[[link](#multiline-if-then)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    if some_condition then\n      ...\n    end\n\n    # good\n    if some_condition\n      ...\n    end\n    ```\n\n* \u003ca name=\"multiline-while-until\"\u003e\u003c/a\u003eNever use `do` for multi-line `while` or\n    `until`.\u003csup\u003e[[link](#multiline-while-until)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    while x \u003e 5 do\n      ...\n    end\n\n    until x \u003e 5 do\n      ...\n    end\n\n    # good\n    while x \u003e 5\n      ...\n    end\n\n    until x \u003e 5\n      ...\n    end\n    ```\n\n* \u003ca name=\"no-and-or\"\u003e\u003c/a\u003eThe `and`, `or`, and `not` keywords are banned. It's\n    just not worth it. Always use `\u0026\u0026`, `||`, and `!` instead.\n    \u003csup\u003e[[link](#no-and-or)]\u003c/sup\u003e\n\n* \u003ca name=\"only-simple-if-unless\"\u003e\u003c/a\u003eModifier `if/unless` usage is okay when\n    the body is simple, the condition is simple, and the whole thing fits on\n    one line. Otherwise, avoid modifier `if/unless`.\n    \u003csup\u003e[[link](#only-simple-if-unless)]\u003c/sup\u003e\n\n    ```ruby\n    # bad - this doesn't fit on one line\n    add_trebuchet_experiments_on_page(request_opts[:trebuchet_experiments_on_page]) if request_opts[:trebuchet_experiments_on_page] \u0026\u0026 !request_opts[:trebuchet_experiments_on_page].empty?\n\n    # okay\n    if request_opts[:trebuchet_experiments_on_page] \u0026\u0026\n         !request_opts[:trebuchet_experiments_on_page].empty?\n\n      add_trebuchet_experiments_on_page(request_opts[:trebuchet_experiments_on_page])\n    end\n\n    # bad - this is complex and deserves multiple lines and a comment\n    parts[i] = part.to_i(INTEGER_BASE) if !part.nil? \u0026\u0026 [0, 2, 3].include?(i)\n\n    # okay\n    return if reconciled?\n    ```\n\n* \u003ca name=\"no-unless-with-else\"\u003e\u003c/a\u003eNever use `unless` with `else`. Rewrite\n    these with the positive case first.\u003csup\u003e[[link](#no-unless-with-else)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    unless success?\n      puts 'failure'\n    else\n      puts 'success'\n    end\n\n    # good\n    if success?\n      puts 'success'\n    else\n      puts 'failure'\n    end\n    ```\n\n* \u003ca name=\"unless-with-multiple-conditions\"\u003e\u003c/a\u003eAvoid `unless` with multiple\n    conditions.\u003csup\u003e[[link](#unless-with-multiple-conditions)]\u003c/sup\u003e\n\n    ```ruby\n      # bad\n      unless foo? \u0026\u0026 bar?\n        ...\n      end\n\n      # okay\n      if !(foo? \u0026\u0026 bar?)\n        ...\n      end\n    ```\n\n* \u003ca name=\"unless-with-comparison-operator\"\u003e\u003c/a\u003eAvoid `unless` with comparison operators if you can use `if` with an opposing comparison operator.\u003csup\u003e[[link](#unless-with-comparison-operator)]\u003c/sup\u003e\n\n    ```ruby\n      # bad\n      unless x == 10\n        ...\n      end\n\n      # good\n      if x != 10\n        ...\n      end\n\n      # bad\n      unless x \u003c 10\n        ...\n      end\n\n      # good\n      if x \u003e= 10\n        ...\n      end\n\n      # ok\n      unless x === 10\n        ...\n      end\n    ```\n\n* \u003ca name=\"parens-around-conditions\"\u003e\u003c/a\u003eDon't use parentheses around the\n    condition of an `if/unless/while`.\n    \u003csup\u003e[[link](#parens-around-conditions)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    if (x \u003e 10)\n      ...\n    end\n\n    # good\n    if x \u003e 10\n      ...\n    end\n\n    ```\n\n### Ternary operator\n\n* \u003ca name=\"avoid-complex-ternary\"\u003e\u003c/a\u003eAvoid the ternary operator (`?:`) except\n    in cases where all expressions are extremely trivial. However, do use the\n    ternary operator(`?:`) over `if/then/else/end` constructs for single line\n    conditionals.\u003csup\u003e[[link](#avoid-complex-ternary)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    result = if some_condition then something else something_else end\n\n    # good\n    result = some_condition ? something : something_else\n    ```\n\n* \u003ca name=\"no-nested-ternaries\"\u003e\u003c/a\u003eUse one expression per branch in a ternary\n    operator. This also means that ternary operators must not be nested. Prefer\n    `if/else` constructs in these cases.\u003csup\u003e[[link](#no-nested-ternaries)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else\n\n    # good\n    if some_condition\n      nested_condition ? nested_something : nested_something_else\n    else\n      something_else\n    end\n    ```\n\n* \u003ca name=\"single-condition-ternary\"\u003e\u003c/a\u003eAvoid multiple conditions in ternaries.\n    Ternaries are best used with single conditions.\n    \u003csup\u003e[[link](#single-condition-ternary)]\u003c/sup\u003e\n\n* \u003ca name=\"no-multiline-ternaries\"\u003e\u003c/a\u003eAvoid multi-line `?:` (the ternary\n    operator), use `if/then/else/end` instead.\n    \u003csup\u003e[[link](#no-multiline-ternaries)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    some_really_long_condition_that_might_make_you_want_to_split_lines ?\n      something : something_else\n\n    # good\n    if some_really_long_condition_that_might_make_you_want_to_split_lines\n      something\n    else\n      something_else\n    end\n    ```\n\n### Nested conditionals\n\n* \u003ca name=\"no-nested-conditionals\"\u003e\u003c/a\u003e\n  Avoid the use of nested conditionals for flow of control.\n  ([More on this][avoid-else-return-early].) \u003csup\u003e[[link](#no-nested-conditionals)]\u003c/sup\u003e\n\n  Prefer a guard clause when you can assert invalid data. A guard clause\n  is a conditional statement at the top of a function that returns as soon\n  as it can.\n\n  The general principles boil down to:\n  * Return immediately once you know your function cannot do anything more.\n  * Reduce nesting and indentation in the code by returning early. This makes\n  the code easier to read and requires less mental bookkeeping on the part\n  of the reader to keep track of `else` branches.\n  * The core or most important flows should be the least indented.\n\n  ```ruby\n  # bad\n  def compute\n    server = find_server\n    if server\n      client = server.client\n      if client\n        request = client.make_request\n        if request\n           process_request(request)\n        end\n      end\n    end\n  end\n\n  # good\n  def compute\n    server = find_server\n    return unless server\n    client = server.client\n    return unless client\n    request = client.make_request\n    return unless request\n    process_request(request)\n  end\n  ```\n\n  Prefer `next` in loops instead of conditional blocks.\n\n  ```ruby\n  # bad\n  [0, 1, 2, 3].each do |item|\n    if item \u003e 1\n      puts item\n    end\n  end\n\n  # good\n  [0, 1, 2, 3].each do |item|\n    next unless item \u003e 1\n    puts item\n  end\n  ```\n\n  See also the section \"Guard Clause\", p68-70 in Beck, Kent.\n  *Implementation Patterns*. Upper Saddle River: Addison-Wesley, 2008, which\n  has inspired some of the content above.\n\n## Syntax\n\n* \u003ca name=\"no-for\"\u003e\u003c/a\u003eNever use `for`, unless you know exactly why. Most of the\n    time iterators should be used instead. `for` is implemented in terms of\n    `each` (so you're adding a level of indirection), but with a twist - `for`\n    doesn't introduce a new scope (unlike `each`) and variables defined in its\n    block will be visible outside it.\u003csup\u003e[[link](#no-for)]\u003c/sup\u003e\n\n    ```ruby\n    arr = [1, 2, 3]\n\n    # bad\n    for elem in arr do\n      puts elem\n    end\n\n    # good\n    arr.each { |elem| puts elem }\n    ```\n\n* \u003ca name=\"single-line-blocks\"\u003e\u003c/a\u003ePrefer `{...}` over `do...end` for\n    single-line blocks.  Avoid using `{...}` for multi-line blocks (multiline\n    chaining is always ugly). Always use `do...end` for \"control flow\" and\n    \"method definitions\" (e.g. in Rakefiles and certain DSLs).  Avoid `do...end`\n    when chaining.\u003csup\u003e[[link](#single-line-blocks)]\u003c/sup\u003e\n\n    ```ruby\n    names = [\"Bozhidar\", \"Steve\", \"Sarah\"]\n\n    # good\n    names.each { |name| puts name }\n\n    # bad\n    names.each do |name| puts name end\n\n    # good\n    names.each do |name|\n      puts name\n      puts 'yay!'\n    end\n\n    # bad\n    names.each { |name|\n      puts name\n      puts 'yay!'\n    }\n\n    # good\n    names.select { |name| name.start_with?(\"S\") }.map { |name| name.upcase }\n\n    # bad\n    names.select do |name|\n      name.start_with?(\"S\")\n    end.map { |name| name.upcase }\n    ```\n\n    Some will argue that multiline chaining would look okay with the use of\n    `{...}`, but they should ask themselves if this code is really readable and\n    whether the block's content can be extracted into nifty methods.\n\n* \u003ca name=\"self-assignment\"\u003e\u003c/a\u003eUse shorthand self assignment operators\n    whenever applicable.\u003csup\u003e[[link](#self-assignment)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    x = x + y\n    x = x * y\n    x = x**y\n    x = x / y\n    x = x || y\n    x = x \u0026\u0026 y\n\n    # good\n    x += y\n    x *= y\n    x **= y\n    x /= y\n    x ||= y\n    x \u0026\u0026= y\n    ```\n\n* \u003ca name=\"semicolons\"\u003e\u003c/a\u003eAvoid semicolons except for in single line class\n    definitions. When it is appropriate to use a semicolon, it should be\n    directly adjacent to the statement it terminates: there should be no\n    space before the semicolon.\u003csup\u003e[[link](#semicolons)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    puts 'foobar'; # superfluous semicolon\n    puts 'foo'; puts 'bar' # two expressions on the same line\n\n    # good\n    puts 'foobar'\n\n    puts 'foo'\n    puts 'bar'\n\n    puts 'foo', 'bar' # this applies to puts in particular\n    ```\n\n* \u003ca name=\"colon-use\"\u003e\u003c/a\u003eUse :: only to reference constants(this includes\n    classes and modules) and constructors (like Array() or Nokogiri::HTML()).\n    Do not use :: for regular method invocation.\u003csup\u003e[[link](#colon-use)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    SomeClass::some_method\n    some_object::some_method\n\n    # good\n    SomeClass.some_method\n    some_object.some_method\n    SomeModule::SomeClass::SOME_CONST\n    SomeModule::SomeClass()\n    ```\n\n* \u003ca name=\"redundant-return\"\u003e\u003c/a\u003eAvoid `return` where not required.\n    \u003csup\u003e[[link](#redundant-return)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    def some_method(some_arr)\n      return some_arr.size\n    end\n\n    # good\n    def some_method(some_arr)\n      some_arr.size\n    end\n    ```\n\n* \u003ca name=\"assignment-in-conditionals\"\u003e\u003c/a\u003eDon't use the return value of `=` in\n    conditionals\u003csup\u003e[[link](#assignment-in-conditionals)]\u003c/sup\u003e\n\n    ```ruby\n    # bad - shows intended use of assignment\n    if (v = array.grep(/foo/))\n      ...\n    end\n\n    # bad\n    if v = array.grep(/foo/)\n      ...\n    end\n\n    # good\n    v = array.grep(/foo/)\n    if v\n      ...\n    end\n\n    ```\n\n* \u003ca name=\"double-pipe-for-uninit\"\u003e\u003c/a\u003eUse `||=` freely to initialize variables.\n    \u003csup\u003e[[link](#double-pipe-for-uninit)]\u003c/sup\u003e\n\n    ```ruby\n    # set name to Bozhidar, only if it's nil or false\n    name ||= 'Bozhidar'\n    ```\n\n* \u003ca name=\"no-double-pipes-for-bools\"\u003e\u003c/a\u003eDon't use `||=` to initialize boolean\n    variables. (Consider what would happen if the current value happened to be\n    `false`.)\u003csup\u003e[[link](#no-double-pipes-for-bools)]\u003c/sup\u003e\n\n    ```ruby\n    # bad - would set enabled to true even if it was false\n    enabled ||= true\n\n    # good\n    enabled = true if enabled.nil?\n    ```\n\n* \u003ca name=\"lambda-calls\"\u003e\u003c/a\u003eUse `.call` explicitly when calling lambdas.\n    \u003csup\u003e[[link](#lambda-calls)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    lambda.(x, y)\n\n    # good\n    lambda.call(x, y)\n    ```\n\n* \u003ca name=\"no-cryptic-perl\"\u003e\u003c/a\u003eAvoid using Perl-style special variables (like\n    `$0-9`, `$`, etc. ). They are quite cryptic and their use in anything but\n    one-liner scripts is discouraged. Prefer long form versions such as\n    `$PROGRAM_NAME`.\u003csup\u003e[[link](#no-cryptic-perl)]\u003c/sup\u003e\n\n* \u003ca name=\"single-action-blocks\"\u003e\u003c/a\u003eWhen a method block takes only one\n    argument, and the body consists solely of reading an attribute or calling\n    one method with no arguments, use the `\u0026:` shorthand.\n    \u003csup\u003e[[link](#single-action-blocks)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    bluths.map { |bluth| bluth.occupation }\n    bluths.select { |bluth| bluth.blue_self? }\n\n    # good\n    bluths.map(\u0026:occupation)\n    bluths.select(\u0026:blue_self?)\n    ```\n\n* \u003ca name=\"redundant-self\"\u003e\u003c/a\u003ePrefer `some_method` over `self.some_method` when\n    calling a method on the current instance.\u003csup\u003e[[link](#redundant-self)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    def end_date\n      self.start_date + self.nights\n    end\n\n    # good\n    def end_date\n      start_date + nights\n    end\n    ```\n\n    In the following three common cases, `self.` is required by the language\n    and is good to use:\n\n    1. When defining a class method: `def self.some_method`.\n    2. The *left hand side* when calling an assignment method, including assigning\n       an attribute when `self` is an ActiveRecord model: `self.guest = user`.\n    3. Referencing the current instance's class: `self.class`.\n\n* \u003ca name=\"freeze-constants\"\u003e\u003c/a\u003eWhen defining an object of any mutable\n    type meant to be a constant, make sure to call `freeze` on it. Common\n    examples are strings, arrays, and hashes.\n    ([More on this][ruby-freeze].)\u003csup\u003e[[link](#freeze-constants)]\u003c/sup\u003e\n\n    The reason is that Ruby constants are actually mutable. Calling `freeze`\n    ensures they are not mutated and are therefore truly constant and\n    attempting to modify them will raise an exception. For strings, this allows\n    older versions of Ruby below 2.2 to intern them.\n\n    ```ruby\n    # bad\n    class Color\n      RED = 'red'\n      BLUE = 'blue'\n      GREEN = 'green'\n\n      ALL_COLORS = [\n        RED,\n        BLUE,\n        GREEN,\n      ]\n\n      COLOR_TO_RGB = {\n        RED =\u003e 0xFF0000,\n        BLUE =\u003e 0x0000FF,\n        GREEN =\u003e 0x00FF00,\n      }\n    end\n\n    # good\n    class Color\n      RED = 'red'.freeze\n      BLUE = 'blue'.freeze\n      GREEN = 'green'.freeze\n\n      ALL_COLORS = [\n        RED,\n        BLUE,\n        GREEN,\n      ].freeze\n\n      COLOR_TO_RGB = {\n        RED =\u003e 0xFF0000,\n        BLUE =\u003e 0x0000FF,\n        GREEN =\u003e 0x00FF00,\n      }.freeze\n    end\n    ```\n\n## Naming\n\n* \u003ca name=\"snake-case\"\u003e\u003c/a\u003eUse `snake_case` for methods and variables.\n    \u003csup\u003e[[link](#snake-case)]\u003c/sup\u003e\n\n* \u003ca name=\"camel-case\"\u003e\u003c/a\u003eUse `CamelCase` for classes and modules. (Keep\n    acronyms like HTTP, RFC, XML uppercase.)\n    \u003csup\u003e[[link](#camel-case)]\u003c/sup\u003e\n\n* \u003ca name=\"screaming-snake-case\"\u003e\u003c/a\u003eUse `SCREAMING_SNAKE_CASE` for other\n    constants.\u003csup\u003e[[link](#screaming-snake-case)]\u003c/sup\u003e\n\n* \u003ca name=\"predicate-method-names\"\u003e\u003c/a\u003eThe names of predicate methods (methods\n    that return a boolean value) should end in a question mark.\n    (i.e. `Array#empty?`).\u003csup\u003e[[link](#predicate-method-names)]\u003c/sup\u003e\n\n* \u003ca name=\"bang-methods\"\u003e\u003c/a\u003eThe names of potentially \"dangerous\" methods\n    (i.e. methods that modify `self` or the arguments, `exit!`, etc.) should\n    end with an exclamation mark. Bang methods should only exist if a non-bang\n    method exists. ([More on this][ruby-naming-bang].)\n    \u003csup\u003e[[link](#bang-methods)]\u003c/sup\u003e\n\n* \u003ca name=\"throwaway-variables\"\u003e\u003c/a\u003eName throwaway variables `_`.\n    \u003csup\u003e[[link](#throwaway-variables)]\u003c/sup\u003e\n\n    ```ruby\n    version = '3.2.1'\n    major_version, minor_version, _ = version.split('.')\n    ```\n\n## Classes\n\n* \u003ca name=\"avoid-class-variables\"\u003e\u003c/a\u003eAvoid the usage of class (`@@`) variables\n    due to their \"nasty\" behavior in inheritance.\n    \u003csup\u003e[[link](#avoid-class-variables)]\u003c/sup\u003e\n\n    ```ruby\n    class Parent\n      @@class_var = 'parent'\n\n      def self.print_class_var\n        puts @@class_var\n      end\n    end\n\n    class Child \u003c Parent\n      @@class_var = 'child'\n    end\n\n    Parent.print_class_var # =\u003e will print \"child\"\n    ```\n\n  As you can see all the classes in a class hierarchy actually share one\n  class variable. Class instance variables should usually be preferred\n  over class variables.\n\n* \u003ca name=\"singleton-methods\"\u003e\u003c/a\u003eUse `def self.method` to define singleton\n    methods. This makes the methods more resistant to refactoring changes.\n    \u003csup\u003e[[link](#singleton-methods)]\u003c/sup\u003e\n\n    ```ruby\n    class TestClass\n      # bad\n      def TestClass.some_method\n        ...\n      end\n\n      # good\n      def self.some_other_method\n        ...\n      end\n    ```\n* \u003ca name=\"no-class-self\"\u003e\u003c/a\u003eAvoid `class \u003c\u003c self` except when necessary,\n    e.g. single accessors and aliased attributes.\n    \u003csup\u003e[[link](#no-class-self)]\u003c/sup\u003e\n\n    ```ruby\n    class TestClass\n      # bad\n      class \u003c\u003c self\n        def first_method\n          ...\n        end\n\n        def second_method_etc\n          ...\n        end\n      end\n\n      # good\n      class \u003c\u003c self\n        attr_accessor :per_page\n        alias_method :nwo, :find_by_name_with_owner\n      end\n\n      def self.first_method\n        ...\n      end\n\n      def self.second_method_etc\n        ...\n      end\n    end\n    ```\n\n* \u003ca name=\"access-modifiers\"\u003e\u003c/a\u003eIndent the `public`, `protected`, and\n    `private` methods as much the method definitions they apply to. Leave one\n    blank line above and below them.\u003csup\u003e[[link](#access-modifiers)]\u003c/sup\u003e\n\n    ```ruby\n    class SomeClass\n      def public_method\n        # ...\n      end\n\n      private\n\n      def private_method\n        # ...\n      end\n    end\n    ```\n\n## Exceptions\n\n* \u003ca name=\"exception-flow-control\"\u003e\u003c/a\u003eDon't use exceptions for flow of control.\n    \u003csup\u003e[[link](#exception-flow-control)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    begin\n      n / d\n    rescue ZeroDivisionError\n      puts \"Cannot divide by 0!\"\n    end\n\n    # good\n    if d.zero?\n      puts \"Cannot divide by 0!\"\n    else\n      n / d\n    end\n    ```\n\n* \u003ca name=\"dont-rescue-exception\"\u003e\u003c/a\u003eAvoid rescuing the `Exception` class.\n    \u003csup\u003e[[link](#dont-rescue-exception)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    begin\n      # an exception occurs here\n    rescue Exception\n      # exception handling\n    end\n\n    # good\n    begin\n      # an exception occurs here\n    rescue StandardError\n      # exception handling\n    end\n\n    # acceptable\n    begin\n      # an exception occurs here\n    rescue\n      # exception handling\n    end\n    ```\n\n* \u003ca name=\"redundant-exception\"\u003e\u003c/a\u003eDon't specify `RuntimeError` explicitly in\n    the two argument version of raise. Prefer error sub-classes for clarity and\n    explicit error creation.\u003csup\u003e[[link](#redundant-exception)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    raise RuntimeError, 'message'\n\n    # better - RuntimeError is implicit here\n    raise 'message'\n\n    # best\n    class MyExplicitError \u003c RuntimeError; end\n    raise MyExplicitError\n    ```\n\n\n* \u003ca name=\"exception-class-messages\"\u003e\u003c/a\u003e\n    Prefer supplying an exception class and a message as two separate arguments\n    to `raise`, instead of an exception instance.\n    \u003csup\u003e[[link](#exception-class-messages)]\u003c/sup\u003e\n\n    ```Ruby\n    # bad\n    raise SomeException.new('message')\n    # Note that there is no way to do `raise SomeException.new('message'), backtrace`.\n\n    # good\n    raise SomeException, 'message'\n    # Consistent with `raise SomeException, 'message', backtrace`.\n    ```\n\n\n* \u003ca name=\"rescue-as-modifier\"\u003e\u003c/a\u003eAvoid using rescue in its modifier form.\n    \u003csup\u003e[[link](#rescue-as-modifier)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    read_file rescue handle_error($!)\n\n    # good\n    begin\n      read_file\n    rescue Errno:ENOENT =\u003e ex\n      handle_error(ex)\n    end\n    ```\n\n## Collections\n\n* \u003ca name=\"map-over-collect\"\u003e\u003c/a\u003ePrefer `map` over\n    `collect`.\u003csup\u003e[[link](#map-over-collect)]\u003c/sup\u003e\n\n* \u003ca name=\"detect-over-find\"\u003e\u003c/a\u003ePrefer `detect` over `find`. The use of `find`\n    is ambiguous with regard to ActiveRecord's `find` method - `detect` makes\n    clear that you're working with a Ruby collection, not an AR object.\n    \u003csup\u003e[[link](#detect-over-find)]\u003c/sup\u003e\n\n* \u003ca name=\"reduce-over-inject\"\u003e\u003c/a\u003ePrefer `reduce` over `inject`.\n    \u003csup\u003e[[link](#reduce-over-inject)]\u003c/sup\u003e\n\n* \u003ca name=\"size-over-count\"\u003e\u003c/a\u003ePrefer `size` over either `length` or `count`\n    for performance reasons.\u003csup\u003e[[link](#size-over-count)]\u003c/sup\u003e\n\n* \u003ca name=\"empty-collection-literals\"\u003e\u003c/a\u003ePrefer literal array and hash creation\n    notation unless you need to pass parameters to their constructors.\n    \u003csup\u003e[[link](#empty-collection-literals)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    arr = Array.new\n    hash = Hash.new\n\n    # good\n    arr = []\n    hash = {}\n\n    # good because constructor requires parameters\n    x = Hash.new { |h, k| h[k] = {} }\n    ```\n\n* \u003ca name=\"array-join\"\u003e\u003c/a\u003eFavor `Array#join` over `Array#*` for clarity.\n    \u003csup\u003e[[link](#array-join)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    %w(one two three) * ', '\n    # =\u003e 'one, two, three'\n\n    # good\n    %w(one two three).join(', ')\n    # =\u003e 'one, two, three'\n    ```\n\n* \u003ca name=\"symbol-keys\"\u003e\u003c/a\u003eUse symbols instead of strings as hash keys.\n    \u003csup\u003e[[link](#symbol-keys)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    hash = { 'one' =\u003e 1, 'two' =\u003e 2, 'three' =\u003e 3 }\n\n    # good\n    hash = { :one =\u003e 1, :two =\u003e 2, :three =\u003e 3 }\n    ```\n\n* \u003ca name=\"symbol-literals\"\u003e\u003c/a\u003eRelatedly, use plain symbols instead of string\n    symbols when possible.\u003csup\u003e[[link](#symbol-literals)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    :\"symbol\"\n\n    # good\n    :symbol\n    ```\n\n* \u003ca name=\"deprecated-hash-methods\"\u003e\u003c/a\u003eUse `Hash#key?` instead of\n    `Hash#has_key?` and `Hash#value?` instead of `Hash#has_value?`. According\n    to Matz, the longer forms are considered deprecated.\n    \u003csup\u003e[[link](#deprecated-hash-methods)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    hash.has_key?(:test)\n    hash.has_value?(value)\n\n    # good\n    hash.key?(:test)\n    hash.value?(value)\n    ```\n\n* \u003ca name=\"multiline-hashes\"\u003e\u003c/a\u003eUse multi-line hashes when it makes the code\n    more readable, and use trailing commas to ensure that parameter changes\n    don't cause extraneous diff lines when the logic has not otherwise changed.\n    \u003csup\u003e[[link](#multiline-hashes)]\u003c/sup\u003e\n\n    ```ruby\n    hash = {\n      :protocol =\u003e 'https',\n      :only_path =\u003e false,\n      :controller =\u003e :users,\n      :action =\u003e :set_password,\n      :redirect =\u003e @redirect_url,\n      :secret =\u003e @secret,\n    }\n    ```\n\n* \u003ca name=\"array-trailing-comma\"\u003e\u003c/a\u003eUse a trailing comma in an `Array` that\n    spans more than 1 line\u003csup\u003e[[link](#array-trailing-comma)]\u003c/sup\u003e\n\n    ```ruby\n    # good\n    array = [1, 2, 3]\n\n    # good\n    array = [\n      \"car\",\n      \"bear\",\n      \"plane\",\n      \"zoo\",\n    ]\n    ```\n\n## Strings\n\n* \u003ca name=\"string-interpolation\"\u003e\u003c/a\u003ePrefer string interpolation instead of\n    string concatenation:\u003csup\u003e[[link](#string-interpolation)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    email_with_name = user.name + ' \u003c' + user.email + '\u003e'\n\n    # good\n    email_with_name = \"#{user.name} \u003c#{user.email}\u003e\"\n    ```\n\n  Furthermore, keep in mind Ruby 1.9-style interpolation. Let's say you are\n  composing cache keys like this:\n\n    ```ruby\n    CACHE_KEY = '_store'\n\n    cache.write(@user.id + CACHE_KEY)\n    ```\n\n    Prefer string interpolation instead of string concatenation:\n\n    ```ruby\n    CACHE_KEY = '%d_store'\n\n    cache.write(CACHE_KEY % @user.id)\n    ```\n\n* \u003ca name=\"string-concatenation\"\u003e\u003c/a\u003eAvoid using `String#+` when you need to\n    construct large data chunks. Instead, use `String#\u003c\u003c`. Concatenation mutates\n    the string instance in-place  and is always faster than `String#+`, which\n    creates a bunch of new string objects.\u003csup\u003e[[link](#string-concatenation)]\u003c/sup\u003e\n\n    ```ruby\n    # good and also fast\n    story = ''\n    story \u003c\u003c 'The Ugly Duckling'\n\n    paragraphs.each do |paragraph|\n      story \u003c\u003c paragraph\n    end\n    ```\n\n* \u003ca name=\"multi-line-strings\"\u003e\u003c/a\u003eUse `\\` at the end of the line instead of `+`\n    or `\u003c\u003c` to concatenate multi-line strings.\n    \u003csup\u003e[[link](#multi-line-strings)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    \"Some string is really long and \" +\n      \"spans multiple lines.\"\n\n    \"Some string is really long and \" \u003c\u003c\n      \"spans multiple lines.\"\n\n    # good\n    \"Some string is really long and \" \\\n      \"spans multiple lines.\"\n    ```\n\n## Regular Expressions\n\n* \u003ca name=\"regex-named-groups\"\u003e\u003c/a\u003eAvoid using `$1-9` as it can be hard to track\n    what they contain. Named groups can be used instead.\n    \u003csup\u003e[[link](#regex-named-groups)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    /(regexp)/ =~ string\n    ...\n    process $1\n\n    # good\n    /(?\u003cmeaningful_var\u003eregexp)/ =~ string\n    ...\n    process meaningful_var\n    ```\n\n* \u003ca name=\"caret-and-dollar-regexp\"\u003e\u003c/a\u003eBe careful with `^` and `$` as they\n    match start/end of line, not string endings.  If you want to match the whole\n    string use: `\\A` and `\\z`.\u003csup\u003e[[link](#caret-and-dollar-regexp)]\u003c/sup\u003e\n\n    ```ruby\n    string = \"some injection\\nusername\"\n    string[/^username$/]   # matches\n    string[/\\Ausername\\z/] # don't match\n    ```\n\n* \u003ca name=\"comment-regexes\"\u003e\u003c/a\u003eUse `x` modifier for complex regexps. This makes\n    them more readable and you can add some useful comments. Just be careful as\n    spaces are ignored.\u003csup\u003e[[link](#comment-regexes)]\u003c/sup\u003e\n\n    ```ruby\n    regexp = %r{\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## Percent Literals\n\n* \u003ca name=\"percent-literal-delimiters\"\u003e\u003c/a\u003ePrefer parentheses over curly\n    braces, brackets, or pipes when using `%`-literal delimiters for\n    consistency, and because the behavior of `%`-literals is closer to method\n    calls than the alternatives.\u003csup\u003e[[link](#percent-literal-delimiters)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    %w[date locale]\n    %w{date locale}\n    %w|date locale|\n\n    # good\n    %w(date locale)\n    ```\n\n* \u003ca name=\"percent-w\"\u003e\u003c/a\u003eUse `%w` freely.\u003csup\u003e[[link](#percent-w)]\u003c/sup\u003e\n\n    ```ruby\n    STATES = %w(draft open closed)\n    ```\n\n* \u003ca name=\"percent-parens\"\u003e\u003c/a\u003eUse `%()` for single-line strings which require\n    both interpolation and embedded double-quotes. For multi-line strings,\n    prefer heredocs.\u003csup\u003e[[link](#percent-parens)]\u003c/sup\u003e\n\n    ```ruby\n    # bad - no interpolation needed\n    %(Welcome, Jane!)\n    # should be 'Welcome, Jane!'\n\n    # bad - no double-quotes\n    %(This is #{quality} style)\n    # should be \"This is #{quality} style\"\n\n    # bad - multiple lines\n    %(Welcome, Jane!\\nPlease enjoy your stay at #{location}\\nCheers!)\n    # should be a heredoc.\n\n    # good - requires interpolation, has quotes, single line\n    %(Welcome, #{name}!)\n    ```\n\n* \u003ca name=\"percent-r\"\u003e\u003c/a\u003eUse `%r` only for regular expressions matching *more\n    than* one '/' character.\u003csup\u003e[[link](#percent-r)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    %r(\\s+)\n\n    # still bad\n    %r(^/(.*)$)\n    # should be /^\\/(.*)$/\n\n    # good\n    %r(^/blog/2011/(.*)$)\n    ```\n\n* \u003ca name=\"percent-x\"\u003e\u003c/a\u003eAvoid the use of %x unless you're going to invoke a\n    command with backquotes in it (which is rather unlikely).\n    \u003csup\u003e[[link](#percent-x)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    date = %x(date)\n\n    # good\n    date = `date`\n    echo = %x(echo `date`)\n    ```\n\n## Rails\n\n* \u003ca name=\"next-line-return\"\u003e\u003c/a\u003eWhen immediately returning after calling\n    `render` or `redirect_to`, put `return` on the next line, not the same line.\n    \u003csup\u003e[[link](#next-line-return)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    render :text =\u003e 'Howdy' and return\n\n    # good\n    render :text =\u003e 'Howdy'\n    return\n\n    # still bad\n    render :text =\u003e 'Howdy' and return if foo.present?\n\n    # good\n    if foo.present?\n      render :text =\u003e 'Howdy'\n      return\n    end\n    ```\n\n### Scopes\n* \u003ca name=\"scope-lambda\"\u003e\u003c/a\u003eWhen defining ActiveRecord model scopes, wrap the\n    relation in a `lambda`.  A naked relation forces a database connection to be\n    established at class load time (instance startup).\n    \u003csup\u003e[[link](#scope-lambda)]\u003c/sup\u003e\n\n    ```ruby\n    # bad\n    scope :foo, where(:bar =\u003e 1)\n\n    # good\n    scope :foo, -\u003e { where(:bar =\u003e 1) }\n    ```\n\n## Be Consistent\n\n\u003e If you're editing code, take a few minutes to look at the code around you and\n\u003e determine its style. If they use spaces around all their arithmetic\n\u003e operators, you should too. If their comments have little boxes of hash marks\n\u003e around them, make your comments have little boxes of hash marks around them\n\u003e too.\n\n\u003e The point of having style guidelines is to have a common vocabulary of coding\n\u003e so people can concentrate on what you're saying rather than on how you're\n\u003e saying it. We present global style rules here so people know the vocabulary,\n\u003e but local style is also important. If code you add to a file looks\n\u003e drastically different from the existing code around it, it throws readers out\n\u003e of their rhythm when they go to read it. Avoid this.\n\n\u0026mdash;[Google C++ Style Guide][google-c++]\n\n[airbnb-javascript]: https://github.com/airbnb/javascript\n[rubocop-guide]: https://github.com/rubocop-hq/ruby-style-guide\n[github-ruby]: https://github.com/styleguide/ruby\n[google-c++]: https://google.github.io/styleguide/cppguide.html\n[google-c++-comments]: https://google.github.io/styleguide/cppguide.html#Comments\n[google-python-comments]: https://google.github.io/styleguide/pyguide.html#Comments\n[ruby-naming-bang]: https://davidablack.net/dablog.html#2007/8/15/bang-methods-or-danger-will-rubyist\n[ruby-freeze]: https://blog.honeybadger.io/when-to-use-freeze-and-frozen-in-ruby/\n[avoid-else-return-early]: http://blog.timoxley.com/post/47041269194/avoid-else-return-early\n\n## Translation\n\n  This style guide is also available in other languages:\n\n  - ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Chinese (Simplified)**: [1c7/ruby-airbnb](https://github.com/1c7/ruby-airbnb)\n","funding_links":[],"categories":["Ruby","Programming Languages","Uncategorized","代码规范\u0026设计模式","Ruby Learning Resources","Best Practice ##","Coding Style","🎨 Coding Style","📕 Guia de Estilo.","Styleguides","Resources","Code quality","Python Frameworks and Tools"],"sub_categories":["Ruby","Uncategorized","Coding Styles ###","Interfaces","Other important resources","Vue","E-Books","Mesh networks","JavaScript Libraries for Machine Learning"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fairbnb%2Fruby","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fairbnb%2Fruby","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fairbnb%2Fruby/lists"}