CINXE.COM
Active Support Core Extensions — Ruby on Rails Guides
<!doctype html> <html dir="ltr" lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Active Support Core Extensions — Ruby on Rails Guides</title> <link rel="stylesheet" type="text/css" href="stylesheets/style-071e355820fc155a5c40ef8a1c0c4971.css" data-turbo-track="reload"> <link rel="stylesheet" type="text/css" href="stylesheets/print-a87ee66d50ce96bb83ac082f1249fe3e.css" media="print"> <link rel="stylesheet" type="text/css" href="stylesheets/highlight-a0d2133dd0073968b2d33b1f1360a2a3.css" data-turbo-track="reload"> <link rel="icon" href="images/favicon.ico" sizes="any"> <link rel="apple-touch-icon" href="images/icon.png"> <script src="javascripts/@hotwired--turbo-764f59c7edbeb902a9068c0340dd274e.js" data-turbo-track="reload"></script> <script src="javascripts/clipboard-8b7aed6f069f0cf58eeae353cd2f898b.js" data-turbo-track="reload"></script> <script src="javascripts/guides-897790ae3777ddd81bd4953f7ec99835.js" data-turbo-track="reload"></script> <meta property="og:title" content="Active Support Core Extensions — Ruby on Rails Guides" /> <meta name="description" content="Active Support Core ExtensionsActive Support is the Ruby on Rails component responsible for providing Ruby language extensions and utilities.It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself.After reading this guide, you will know: What Core Extensions are. How to load all extensions. How to cherry-pick just the extensions you want. What extensions Active Support provides." /> <meta property="og:description" content="Active Support Core ExtensionsActive Support is the Ruby on Rails component responsible for providing Ruby language extensions and utilities.It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself.After reading this guide, you will know: What Core Extensions are. How to load all extensions. How to cherry-pick just the extensions you want. What extensions Active Support provides." /> <meta property="og:locale" content="en_US" /> <meta property="og:site_name" content="Ruby on Rails Guides" /> <meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" /> <meta property="og:type" content="website" /> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Heebo:wght@100..900&family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <meta name="theme-color" content="#C81418"> </head> <body dir="ltr" class="guide no-js"> <script> document.body.classList.remove('no-js') </script> <a id="main-skip-link" href="#main" class="skip-link" data-turbo="false"> Skip to main content </a> <div id="mobile-navigation-bar"> <div class="wrapper"> <strong class="more-info-label">More at <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong> <button type="button" class="js-only red-button more-info-button" id="more-info" aria-controls="more-info-links" aria-expanded="false"> More Ruby on Rails </button> <ul id="more-info-links" class="more-info-links hidden"> <li class="more-info"><a href="https://rubyonrails.org/blog">Blog</a></li> <li class="more-info"><a href="https://guides.rubyonrails.org/">Guides</a></li> <li class="more-info"><a href="https://api.rubyonrails.org/">API</a></li> <li class="more-info"><a href="https://discuss.rubyonrails.org/">Forum</a></li> <li class="more-info"><a href="https://github.com/rails/rails">Contribute on GitHub</a></li> </ul> </div> </div> <header id="page-header"> <div class="wrapper clearfix"> <nav id="feature-nav"> <div class="header-logo"> <a href="index.html" title="Guides home for v8.0.0 Guides">Guides</a> <span id="version-switcher" class="js-only"> <label for="version-switcher-select">Version: <span class="visibly-hidden">pick from the list to go to that Rails version's guides</span></label> <select id="version-switcher-select" class="guides-version"> <option value="https://edgeguides.rubyonrails.org/">Edge</option> <option value="https://guides.rubyonrails.org/v8.0/" selected>8.0</option> <option value="https://guides.rubyonrails.org/v7.2/">7.2</option> <option value="https://guides.rubyonrails.org/v7.1/">7.1</option> <option value="https://guides.rubyonrails.org/v7.0/">7.0</option> <option value="https://guides.rubyonrails.org/v6.1/">6.1</option> <option value="https://guides.rubyonrails.org/v6.0/">6.0</option> <option value="https://guides.rubyonrails.org/v5.2/">5.2</option> <option value="https://guides.rubyonrails.org/v5.1/">5.1</option> <option value="https://guides.rubyonrails.org/v5.0/">5.0</option> <option value="https://guides.rubyonrails.org/v4.2/">4.2</option> <option value="https://guides.rubyonrails.org/v4.1/">4.1</option> <option value="https://guides.rubyonrails.org/v4.0/">4.0</option> <option value="https://guides.rubyonrails.org/v3.2/">3.2</option> <option value="https://guides.rubyonrails.org/v3.1/">3.1</option> <option value="https://guides.rubyonrails.org/v3.0/">3.0</option> <option value="https://guides.rubyonrails.org/v2.3/">2.3</option> </select> </span> </div> <ul class="nav"> <li><a class="nav-item" id="home_nav" href="https://rubyonrails.org/">Home</a></li> <li class="guides-index guides-index-large"> <a href="index.html" id="guides-menu-button" data-aria-controls="guides" data-aria-expanded="false" class="guides-index-item nav-item">Guides Index</a> <div id="guides" class="clearfix" style="display: none;"> <hr /> <dl class="guides-section-container"> <div class="guides-section"> <dt>Start Here</dt> <dd><a href="getting_started.html">Getting Started with Rails</a></dd> </div> <div class="guides-section"> <dt>Models</dt> <dd><a href="active_record_basics.html">Active Record Basics</a></dd> <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd> <dd><a href="active_record_validations.html">Active Record Validations</a></dd> <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd> <dd><a href="association_basics.html">Active Record Associations</a></dd> <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd> <dd><a href="active_model_basics.html">Active Model Basics</a></dd> </div> <div class="guides-section"> <dt>Views</dt> <dd><a href="action_view_overview.html">Action View Overview</a></dd> <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd> <dd><a href="action_view_helpers.html">Action View Helpers</a></dd> <dd><a href="form_helpers.html">Action View Form Helpers</a></dd> </div> <div class="guides-section"> <dt>Controllers</dt> <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd> <dd><a href="routing.html">Rails Routing from the Outside In</a></dd> </div> <div class="guides-section"> <dt>Other Components</dt> <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd> <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd> <dd><a href="action_mailbox_basics.html">Action Mailbox Basics</a></dd> <dd><a href="action_text_overview.html">Action Text Overview</a></dd> <dd><a href="active_job_basics.html">Active Job Basics</a></dd> <dd><a href="active_storage_overview.html">Active Storage Overview</a></dd> <dd><a href="action_cable_overview.html">Action Cable Overview</a></dd> </div> <div class="guides-section"> <dt>Digging Deeper</dt> <dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd> <dd><a href="testing.html">Testing Rails Applications</a></dd> <dd><a href="security.html">Securing Rails Applications</a></dd> <dd><a href="error_reporting.html">Error Reporting in Rails Applications</a></dd> <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd> <dd><a href="configuring.html">Configuring Rails Applications</a></dd> <dd><a href="command_line.html">The Rails Command Line</a></dd> <dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd> <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd> <dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading</a></dd> <dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd> <dd><a href="api_app.html">Using Rails for API-only Applications</a></dd> <dd><a href="tuning_performance_for_deployment.html">Tuning Performance for Deployment</a></dd> </div> <div class="guides-section"> <dt>Advanced Active Record</dt> <dd><a href="active_record_multiple_databases.html">Multiple Databases</a></dd> <dd><a href="active_record_composite_primary_keys.html">Composite Primary Keys</a></dd> </div> <div class="guides-section"> <dt>Extending Rails</dt> <dd><a href="rails_on_rack.html">Rails on Rack</a></dd> <dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd> </div> <div class="guides-section"> <dt>Contributing</dt> <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd> <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd> <dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd> <dd><a href="development_dependencies_install.html">Installing Rails Core Development Dependencies</a></dd> </div> <div class="guides-section"> <dt>Policies</dt> <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd> </div> <div class="guides-section"> <dt>Release Notes</dt> <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd> <dd><a href="7_2_release_notes.html">Version 7.2 - August 2024</a></dd> <dd><a href="7_1_release_notes.html">Version 7.1 - October 2023</a></dd> <dd><a href="7_0_release_notes.html">Version 7.0 - December 2021</a></dd> <dd><a href="6_1_release_notes.html">Version 6.1 - December 2020</a></dd> <dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd> <dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd> <dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd> <dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd> <dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd> <dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd> <dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd> <dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd> <dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd> <dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd> <dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd> <dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd> </div> </dl> </div> </li> <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li> <li class="guides-index guides-index-small js-only"> <label for="guides-selector"> Navigate to a guide: </label> <select id="guides-selector" class="guides-index-item nav-item"> <option value="index.html">Guides Index</option> <optgroup label="Start Here"> <option value="getting_started.html">Getting Started with Rails</option> </optgroup> <optgroup label="Models"> <option value="active_record_basics.html">Active Record Basics</option> <option value="active_record_migrations.html">Active Record Migrations</option> <option value="active_record_validations.html">Active Record Validations</option> <option value="active_record_callbacks.html">Active Record Callbacks</option> <option value="association_basics.html">Active Record Associations</option> <option value="active_record_querying.html">Active Record Query Interface</option> <option value="active_model_basics.html">Active Model Basics</option> </optgroup> <optgroup label="Views"> <option value="action_view_overview.html">Action View Overview</option> <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option> <option value="action_view_helpers.html">Action View Helpers</option> <option value="form_helpers.html">Action View Form Helpers</option> </optgroup> <optgroup label="Controllers"> <option value="action_controller_overview.html">Action Controller Overview</option> <option value="routing.html">Rails Routing from the Outside In</option> </optgroup> <optgroup label="Other Components"> <option value="active_support_core_extensions.html">Active Support Core Extensions</option> <option value="action_mailer_basics.html">Action Mailer Basics</option> <option value="action_mailbox_basics.html">Action Mailbox Basics</option> <option value="action_text_overview.html">Action Text Overview</option> <option value="active_job_basics.html">Active Job Basics</option> <option value="active_storage_overview.html">Active Storage Overview</option> <option value="action_cable_overview.html">Action Cable Overview</option> </optgroup> <optgroup label="Digging Deeper"> <option value="i18n.html">Rails Internationalization (I18n) API</option> <option value="testing.html">Testing Rails Applications</option> <option value="security.html">Securing Rails Applications</option> <option value="error_reporting.html">Error Reporting in Rails Applications</option> <option value="debugging_rails_applications.html">Debugging Rails Applications</option> <option value="configuring.html">Configuring Rails Applications</option> <option value="command_line.html">The Rails Command Line</option> <option value="asset_pipeline.html">The Asset Pipeline</option> <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option> <option value="autoloading_and_reloading_constants.html">Autoloading and Reloading</option> <option value="caching_with_rails.html">Caching with Rails: An Overview</option> <option value="api_app.html">Using Rails for API-only Applications</option> <option value="tuning_performance_for_deployment.html">Tuning Performance for Deployment</option> </optgroup> <optgroup label="Advanced Active Record"> <option value="active_record_multiple_databases.html">Multiple Databases</option> <option value="active_record_composite_primary_keys.html">Composite Primary Keys</option> </optgroup> <optgroup label="Extending Rails"> <option value="rails_on_rack.html">Rails on Rack</option> <option value="generators.html">Creating and Customizing Rails Generators & Templates</option> </optgroup> <optgroup label="Contributing"> <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option> <option value="api_documentation_guidelines.html">API Documentation Guidelines</option> <option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option> <option value="development_dependencies_install.html">Installing Rails Core Development Dependencies</option> </optgroup> <optgroup label="Policies"> <option value="maintenance_policy.html">Maintenance Policy</option> </optgroup> <optgroup label="Release Notes"> <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option> <option value="7_2_release_notes.html">Version 7.2 - August 2024</option> <option value="7_1_release_notes.html">Version 7.1 - October 2023</option> <option value="7_0_release_notes.html">Version 7.0 - December 2021</option> <option value="6_1_release_notes.html">Version 6.1 - December 2020</option> <option value="6_0_release_notes.html">Version 6.0 - August 2019</option> <option value="5_2_release_notes.html">Version 5.2 - April 2018</option> <option value="5_1_release_notes.html">Version 5.1 - April 2017</option> <option value="5_0_release_notes.html">Version 5.0 - June 2016</option> <option value="4_2_release_notes.html">Version 4.2 - December 2014</option> <option value="4_1_release_notes.html">Version 4.1 - April 2014</option> <option value="4_0_release_notes.html">Version 4.0 - June 2013</option> <option value="3_2_release_notes.html">Version 3.2 - January 2012</option> <option value="3_1_release_notes.html">Version 3.1 - August 2011</option> <option value="3_0_release_notes.html">Version 3.0 - August 2010</option> <option value="2_3_release_notes.html">Version 2.3 - March 2009</option> <option value="2_2_release_notes.html">Version 2.2 - November 2008</option> </optgroup> </select> </li> </ul> </nav> </div> </header> <hr class="hide" /> <main id="main"> <article> <header id="feature"> <div class="wrapper"> <h1>Active Support Core Extensions</h1><p>Active Support is the Ruby on Rails component responsible for providing Ruby language extensions and utilities.</p><p>It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself.</p><p>After reading this guide, you will know:</p> <ul> <li>What Core Extensions are.</li> <li>How to load all extensions.</li> <li>How to cherry-pick just the extensions you want.</li> <li>What extensions Active Support provides.</li> </ul> <nav id="column-side" aria-label="Chapter" class="guide-index" data-turbo="false"> <a id="chapter-nav-skip-link" href="#article-body" class="skip-link"> Skip to article body </a> <h2 class="chapter"> <picture aria-hidden="true"> <!-- Using the `source` HTML tag to set the dark theme image --> <source srcset="images/icon_book-close-bookmark-1-wht.svg" media="(prefers-color-scheme: dark)" /> <img src="images/icon_book-close-bookmark-1.svg" alt="Chapter Icon" /> </picture> Chapters </h2> <ol class="chapters"> <li><a href="#how-to-load-core-extensions">How to Load Core Extensions</a> <ul> <li><a href="#stand-alone-active-support">Stand-Alone Active Support</a></li> <li><a href="#active-support-within-a-ruby-on-rails-application">Active Support Within a Ruby on Rails Application</a></li> </ul></li> <li><a href="#extensions-to-all-objects">Extensions to All Objects</a> <ul> <li><a href="#blank-questionmark-and-present-questionmark"><code>blank?</code> and <code>present?</code></a></li> <li><a href="#presence"><code>presence</code></a></li> <li><a href="#duplicable-questionmark"><code>duplicable?</code></a></li> <li><a href="#deep-dup"><code>deep_dup</code></a></li> <li><a href="#try"><code>try</code></a></li> <li><a href="#class-eval-args-block"><code>class_eval(*args, &block)</code></a></li> <li><a href="#acts-like-questionmark-duck"><code>acts_like?(duck)</code></a></li> <li><a href="#to-param"><code>to_param</code></a></li> <li><a href="#to-query"><code>to_query</code></a></li> <li><a href="#with-options"><code>with_options</code></a></li> <li><a href="#json-support">JSON Support</a></li> <li><a href="#instance-variables">Instance Variables</a></li> <li><a href="#silencing-warnings-and-exceptions">Silencing Warnings and Exceptions</a></li> <li><a href="#in-questionmark"><code>in?</code></a></li> </ul></li> <li><a href="#extensions-to-module">Extensions to <code>Module</code></a> <ul> <li><a href="#attributes">Attributes</a></li> <li><a href="#parents">Parents</a></li> <li><a href="#anonymous">Anonymous</a></li> <li><a href="#method-delegation">Method Delegation</a></li> <li><a href="#redefining-methods">Redefining Methods</a></li> </ul></li> <li><a href="#extensions-to-class">Extensions to <code>Class</code></a> <ul> <li><a href="#class-attributes">Class Attributes</a></li> <li><a href="#subclasses-and-descendants">Subclasses and Descendants</a></li> </ul></li> <li><a href="#extensions-to-string">Extensions to <code>String</code></a> <ul> <li><a href="#output-safety">Output Safety</a></li> <li><a href="#remove"><code>remove</code></a></li> <li><a href="#squish"><code>squish</code></a></li> <li><a href="#truncate"><code>truncate</code></a></li> <li><a href="#truncate-bytes"><code>truncate_bytes</code></a></li> <li><a href="#truncate-words"><code>truncate_words</code></a></li> <li><a href="#inquiry"><code>inquiry</code></a></li> <li><a href="#extensions-to-string-starts-with-questionmark-and-ends-with-questionmark"><code>starts_with?</code> and <code>ends_with?</code></a></li> <li><a href="#strip-heredoc"><code>strip_heredoc</code></a></li> <li><a href="#indent"><code>indent</code></a></li> <li><a href="#access">Access</a></li> <li><a href="#inflections">Inflections</a></li> <li><a href="#extensions-to-string-conversions">Conversions</a></li> </ul></li> <li><a href="#extensions-to-symbol">Extensions to <code>Symbol</code></a> <ul> <li><a href="#extensions-to-symbol-starts-with-questionmark-and-ends-with-questionmark"><code>starts_with?</code> and <code>ends_with?</code></a></li> </ul></li> <li><a href="#extensions-to-numeric">Extensions to <code>Numeric</code></a> <ul> <li><a href="#bytes">Bytes</a></li> <li><a href="#extensions-to-numeric-time">Time</a></li> <li><a href="#formatting">Formatting</a></li> </ul></li> <li><a href="#extensions-to-integer">Extensions to <code>Integer</code></a> <ul> <li><a href="#multiple-of-questionmark"><code>multiple_of?</code></a></li> <li><a href="#ordinal"><code>ordinal</code></a></li> <li><a href="#ordinalize"><code>ordinalize</code></a></li> <li><a href="#extensions-to-integer-time">Time</a></li> </ul></li> <li><a href="#extensions-to-bigdecimal">Extensions to <code>BigDecimal</code></a> <ul> <li><a href="#to-s"><code>to_s</code></a></li> </ul></li> <li><a href="#extensions-to-enumerable">Extensions to <code>Enumerable</code></a> <ul> <li><a href="#index-by"><code>index_by</code></a></li> <li><a href="#index-with"><code>index_with</code></a></li> <li><a href="#many-questionmark"><code>many?</code></a></li> <li><a href="#exclude-questionmark"><code>exclude?</code></a></li> <li><a href="#including"><code>including</code></a></li> <li><a href="#excluding"><code>excluding</code></a></li> <li><a href="#pluck"><code>pluck</code></a></li> <li><a href="#pick"><code>pick</code></a></li> </ul></li> <li><a href="#extensions-to-array">Extensions to <code>Array</code></a> <ul> <li><a href="#accessing">Accessing</a></li> <li><a href="#extensions-to-array-extracting">Extracting</a></li> <li><a href="#options-extraction">Options Extraction</a></li> <li><a href="#extensions-to-array-conversions">Conversions</a></li> <li><a href="#wrapping">Wrapping</a></li> <li><a href="#duplicating">Duplicating</a></li> <li><a href="#grouping">Grouping</a></li> </ul></li> <li><a href="#extensions-to-hash">Extensions to <code>Hash</code></a> <ul> <li><a href="#conversions">Conversions</a></li> <li><a href="#merging">Merging</a></li> <li><a href="#deep-duplicating">Deep Duplicating</a></li> <li><a href="#working-with-keys">Working with Keys</a></li> <li><a href="#working-with-values">Working with Values</a></li> <li><a href="#slicing">Slicing</a></li> <li><a href="#extensions-to-hash-extracting">Extracting</a></li> <li><a href="#indifferent-access">Indifferent Access</a></li> </ul></li> <li><a href="#extensions-to-regexp">Extensions to <code>Regexp</code></a> <ul> <li><a href="#multiline-questionmark"><code>multiline?</code></a></li> </ul></li> <li><a href="#extensions-to-range">Extensions to <code>Range</code></a> <ul> <li><a href="#extensions-to-range-to-fs"><code>to_fs</code></a></li> <li><a href="#and-include-questionmark"><code>===</code> and <code>include?</code></a></li> <li><a href="#overlap-questionmark"><code>overlap?</code></a></li> </ul></li> <li><a href="#extensions-to-date">Extensions to <code>Date</code></a> <ul> <li><a href="#extensions-to-date-calculations">Calculations</a></li> </ul></li> <li><a href="#extensions-to-datetime">Extensions to <code>DateTime</code></a> <ul> <li><a href="#extensions-to-datetime-calculations">Calculations</a></li> </ul></li> <li><a href="#extensions-to-time">Extensions to <code>Time</code></a> <ul> <li><a href="#calculations">Calculations</a></li> <li><a href="#time-constructors">Time Constructors</a></li> </ul></li> <li><a href="#extensions-to-file">Extensions to <code>File</code></a> <ul> <li><a href="#atomic-write"><code>atomic_write</code></a></li> </ul></li> <li><a href="#extensions-to-nameerror">Extensions to <code>NameError</code></a></li> <li><a href="#extensions-to-loaderror">Extensions to <code>LoadError</code></a></li> <li><a href="#extensions-to-pathname">Extensions to Pathname</a> <ul> <li><a href="#existence"><code>existence</code></a></li> </ul></li> </ol> </nav> </div> </header> <div class="wrapper"> <div id="column-main"> <section id="article-body"> <h2 id="how-to-load-core-extensions"><a class="anchorlink" href="#how-to-load-core-extensions" data-turbo="false"><span>1</span> How to Load Core Extensions</a></h2><h3 id="stand-alone-active-support"><a class="anchorlink" href="#stand-alone-active-support" data-turbo="false"><span>1.1</span> Stand-Alone Active Support</a></h3><p>In order to have the smallest default footprint possible, Active Support loads the minimum dependencies by default. It is broken in small pieces so that only the desired extensions can be loaded. It also has some convenience entry points to load related extensions in one shot, even everything.</p><p>Thus, after a simple require like:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">require</span> <span class="s2">"active_support"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="require "active_support" ">Copy</button> </div> <p>only the extensions required by the Active Support framework are loaded.</p><h4 id="cherry-picking-a-definition"><a class="anchorlink" href="#cherry-picking-a-definition" data-turbo="false"><span>1.1.1</span> Cherry-picking a Definition</a></h4><p>This example shows how to load <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-with_indifferent_access"><code>Hash#with_indifferent_access</code></a>. This extension enables the conversion of a <code>Hash</code> into an <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/HashWithIndifferentAccess.html"><code>ActiveSupport::HashWithIndifferentAccess</code></a> which permits access to the keys as either strings or symbols.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span> <span class="p">}.</span><span class="nf">with_indifferent_access</span><span class="p">[</span><span class="s2">"a"</span><span class="p">]</span> <span class="c1"># => 1</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ a: 1 }.with_indifferent_access["a"] # => 1 ">Copy</button> </div> <p>For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of <code>with_indifferent_access</code> the note reads:</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb">active_support/core_ext/hash/indifferent_access.rb</a></code>.</p></div><p>That means that you can require it like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">require</span> <span class="s2">"active_support"</span> <span class="nb">require</span> <span class="s2">"active_support/core_ext/hash/indifferent_access"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="require "active_support" require "active_support/core_ext/hash/indifferent_access" ">Copy</button> </div> <p>Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.</p><h4 id="loading-grouped-core-extensions"><a class="anchorlink" href="#loading-grouped-core-extensions" data-turbo="false"><span>1.1.2</span> Loading Grouped Core Extensions</a></h4><p>The next level is to simply load all extensions to <code>Hash</code>. As a rule of thumb, extensions to <code>SomeClass</code> are available in one shot by loading <code>active_support/core_ext/some_class</code>.</p><p>Thus, to load all extensions to <code>Hash</code> (including <code>with_indifferent_access</code>):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">require</span> <span class="s2">"active_support"</span> <span class="nb">require</span> <span class="s2">"active_support/core_ext/hash"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="require "active_support" require "active_support/core_ext/hash" ">Copy</button> </div> <h4 id="loading-all-core-extensions"><a class="anchorlink" href="#loading-all-core-extensions" data-turbo="false"><span>1.1.3</span> Loading All Core Extensions</a></h4><p>You may prefer just to load all core extensions, there is a file for that:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">require</span> <span class="s2">"active_support"</span> <span class="nb">require</span> <span class="s2">"active_support/core_ext"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="require "active_support" require "active_support/core_ext" ">Copy</button> </div> <h4 id="loading-all-active-support"><a class="anchorlink" href="#loading-all-active-support" data-turbo="false"><span>1.1.4</span> Loading All Active Support</a></h4><p>And finally, if you want to have all Active Support available just issue:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">require</span> <span class="s2">"active_support/all"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="require "active_support/all" ">Copy</button> </div> <p>That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via <code>autoload</code>, so it is only loaded if used.</p><h3 id="active-support-within-a-ruby-on-rails-application"><a class="anchorlink" href="#active-support-within-a-ruby-on-rails-application" data-turbo="false"><span>1.2</span> Active Support Within a Ruby on Rails Application</a></h3><p>A Ruby on Rails application loads all Active Support unless <a href="configuring.html#config-active-support-bare"><code>config.active_support.bare</code></a> is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section.</p><h2 id="extensions-to-all-objects"><a class="anchorlink" href="#extensions-to-all-objects" data-turbo="false"><span>2</span> Extensions to All Objects</a></h2><h3 id="blank-questionmark-and-present-questionmark"><a class="anchorlink" href="#blank-questionmark-and-present-questionmark" data-turbo="false"><span>2.1</span> <code>blank?</code> and <code>present?</code></a></h3><p>The following values are considered to be blank in a Rails application:</p> <ul> <li><p><code>nil</code> and <code>false</code>,</p></li> <li><p>strings composed only of whitespace (see note below),</p></li> <li><p>empty arrays and hashes, and</p></li> <li><p>any other object that responds to <code>empty?</code> and is empty.</p></li> </ul> <div class="interstitial info"><p>The predicate for strings uses the Unicode-aware character class <code>[:space:]</code>, so for example U+2029 (paragraph separator) is considered to be whitespace.</p></div><div class="interstitial warning"><p>Note that numbers are not mentioned. In particular, 0 and 0.0 are <strong>not</strong> blank.</p></div><p>For example, this method from <code>ActionController::HttpAuthentication::Token::ControllerMethods</code> uses <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-blank-3F"><code>blank?</code></a> for checking whether a token is present:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">authenticate</span><span class="p">(</span><span class="n">controller</span><span class="p">,</span> <span class="o">&</span><span class="n">login_procedure</span><span class="p">)</span> <span class="n">token</span><span class="p">,</span> <span class="n">options</span> <span class="o">=</span> <span class="n">token_and_options</span><span class="p">(</span><span class="n">controller</span><span class="p">.</span><span class="nf">request</span><span class="p">)</span> <span class="k">unless</span> <span class="n">token</span><span class="p">.</span><span class="nf">blank?</span> <span class="n">login_procedure</span><span class="p">.</span><span class="nf">call</span><span class="p">(</span><span class="n">token</span><span class="p">,</span> <span class="n">options</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def authenticate(controller, &login_procedure) token, options = token_and_options(controller.request) unless token.blank? login_procedure.call(token, options) end end ">Copy</button> </div> <p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-present-3F"><code>present?</code></a> is equivalent to <code>!blank?</code>. This example is taken from <code>ActionDispatch::Http::Cache::Response</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">set_conditional_cache_control!</span> <span class="k">unless</span> <span class="nb">self</span><span class="p">[</span><span class="s2">"Cache-Control"</span><span class="p">].</span><span class="nf">present?</span> <span class="c1"># ...</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def set_conditional_cache_control! unless self["Cache-Control"].present? # ... end end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/blank.rb">active_support/core_ext/object/blank.rb</a></code>.</p></div><h3 id="presence"><a class="anchorlink" href="#presence" data-turbo="false"><span>2.2</span> <code>presence</code></a></h3><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-presence"><code>presence</code></a> method returns its receiver if <code>present?</code>, and <code>nil</code> otherwise. It is useful for idioms like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">host</span> <span class="o">=</span> <span class="n">config</span><span class="p">[</span><span class="ss">:host</span><span class="p">].</span><span class="nf">presence</span> <span class="o">||</span> <span class="s2">"localhost"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="host = config[:host].presence || "localhost" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/blank.rb">active_support/core_ext/object/blank.rb</a></code>.</p></div><h3 id="duplicable-questionmark"><a class="anchorlink" href="#duplicable-questionmark" data-turbo="false"><span>2.3</span> <code>duplicable?</code></a></h3><p>As of Ruby 2.5, most objects can be duplicated via <code>dup</code> or <code>clone</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"foo"</span><span class="p">.</span><span class="nf">dup</span> <span class="c1"># => "foo"</span> <span class="s2">""</span><span class="p">.</span><span class="nf">dup</span> <span class="c1"># => ""</span> <span class="no">Rational</span><span class="p">(</span><span class="mi">1</span><span class="p">).</span><span class="nf">dup</span> <span class="c1"># => (1/1)</span> <span class="no">Complex</span><span class="p">(</span><span class="mi">0</span><span class="p">).</span><span class="nf">dup</span> <span class="c1"># => (0+0i)</span> <span class="mi">1</span><span class="p">.</span><span class="nf">method</span><span class="p">(:</span><span class="o">+</span><span class="p">).</span><span class="nf">dup</span> <span class="c1"># => TypeError (allocator undefined for Method)</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""foo".dup # => "foo" "".dup # => "" Rational(1).dup # => (1/1) Complex(0).dup # => (0+0i) 1.method(:+).dup # => TypeError (allocator undefined for Method) ">Copy</button> </div> <p>Active Support provides <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-duplicable-3F"><code>duplicable?</code></a> to query an object about this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"foo"</span><span class="p">.</span><span class="nf">duplicable?</span> <span class="c1"># => true</span> <span class="s2">""</span><span class="p">.</span><span class="nf">duplicable?</span> <span class="c1"># => true</span> <span class="no">Rational</span><span class="p">(</span><span class="mi">1</span><span class="p">).</span><span class="nf">duplicable?</span> <span class="c1"># => true</span> <span class="no">Complex</span><span class="p">(</span><span class="mi">1</span><span class="p">).</span><span class="nf">duplicable?</span> <span class="c1"># => true</span> <span class="mi">1</span><span class="p">.</span><span class="nf">method</span><span class="p">(:</span><span class="o">+</span><span class="p">).</span><span class="nf">duplicable?</span> <span class="c1"># => false</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""foo".duplicable? # => true "".duplicable? # => true Rational(1).duplicable? # => true Complex(1).duplicable? # => true 1.method(:+).duplicable? # => false ">Copy</button> </div> <div class="interstitial warning"><p>Any class can disallow duplication by removing <code>dup</code> and <code>clone</code> or raising exceptions from them. Thus only <code>rescue</code> can tell whether a given arbitrary object is duplicable. <code>duplicable?</code> depends on the hard-coded list above, but it is much faster than <code>rescue</code>. Use it only if you know the hard-coded list is enough in your use case.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/duplicable.rb">active_support/core_ext/object/duplicable.rb</a></code>.</p></div><h3 id="deep-dup"><a class="anchorlink" href="#deep-dup" data-turbo="false"><span>2.4</span> <code>deep_dup</code></a></h3><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-deep_dup"><code>deep_dup</code></a> method returns a deep copy of a given object. Normally, when you <code>dup</code> an object that contains other objects, Ruby does not <code>dup</code> them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">array</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"string"</span><span class="p">]</span> <span class="n">duplicate</span> <span class="o">=</span> <span class="n">array</span><span class="p">.</span><span class="nf">dup</span> <span class="n">duplicate</span><span class="p">.</span><span class="nf">push</span> <span class="s2">"another-string"</span> <span class="c1"># the object was duplicated, so the element was added only to the duplicate</span> <span class="n">array</span> <span class="c1"># => ["string"]</span> <span class="n">duplicate</span> <span class="c1"># => ["string", "another-string"]</span> <span class="n">duplicate</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">gsub!</span><span class="p">(</span><span class="s2">"string"</span><span class="p">,</span> <span class="s2">"foo"</span><span class="p">)</span> <span class="c1"># first element was not duplicated, it will be changed in both arrays</span> <span class="n">array</span> <span class="c1"># => ["foo"]</span> <span class="n">duplicate</span> <span class="c1"># => ["foo, "another-string"]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="array = ["string"] duplicate = array.dup duplicate.push "another-string" # the object was duplicated, so the element was added only to the duplicate array # => ["string"] duplicate # => ["string", "another-string"] duplicate.first.gsub!("string", "foo") # first element was not duplicated, it will be changed in both arrays array # => ["foo"] duplicate # => ["foo, "another-string"] ">Copy</button> </div> <p>As you can see, after duplicating the <code>Array</code> instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since <code>dup</code> does not make a deep copy, the string inside the array is still the same object.</p><p>If you need a deep copy of an object, you should use <code>deep_dup</code>. Here is an example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">array</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"string"</span><span class="p">]</span> <span class="n">duplicate</span> <span class="o">=</span> <span class="n">array</span><span class="p">.</span><span class="nf">deep_dup</span> <span class="n">duplicate</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">gsub!</span><span class="p">(</span><span class="s2">"string"</span><span class="p">,</span> <span class="s2">"foo"</span><span class="p">)</span> <span class="n">array</span> <span class="c1"># => ["string"]</span> <span class="n">duplicate</span> <span class="c1"># => ["foo"]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="array = ["string"] duplicate = array.deep_dup duplicate.first.gsub!("string", "foo") array # => ["string"] duplicate # => ["foo"] ">Copy</button> </div> <p>If the object is not duplicable, <code>deep_dup</code> will just return it:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">number</span> <span class="o">=</span> <span class="mi">1</span> <span class="n">duplicate</span> <span class="o">=</span> <span class="n">number</span><span class="p">.</span><span class="nf">deep_dup</span> <span class="n">number</span><span class="p">.</span><span class="nf">object_id</span> <span class="o">==</span> <span class="n">duplicate</span><span class="p">.</span><span class="nf">object_id</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="number = 1 duplicate = number.deep_dup number.object_id == duplicate.object_id # => true ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/deep_dup.rb">active_support/core_ext/object/deep_dup.rb</a></code>.</p></div><h3 id="try"><a class="anchorlink" href="#try" data-turbo="false"><span>2.5</span> <code>try</code></a></h3><p>When you want to call a method on an object only if it is not <code>nil</code>, the simplest way to achieve it is with conditional statements, adding unnecessary clutter. The alternative is to use <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-try"><code>try</code></a>. <code>try</code> is like <code>Object#public_send</code> except that it returns <code>nil</code> if sent to <code>nil</code>.</p><p>Here is an example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># without try</span> <span class="k">unless</span> <span class="vi">@number</span><span class="p">.</span><span class="nf">nil?</span> <span class="vi">@number</span><span class="p">.</span><span class="nf">next</span> <span class="k">end</span> <span class="c1"># with try</span> <span class="vi">@number</span><span class="p">.</span><span class="nf">try</span><span class="p">(</span><span class="ss">:next</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# without try unless @number.nil? @number.next end # with try @number.try(:next) ">Copy</button> </div> <p>Another example is this code from <code>ActiveRecord::ConnectionAdapters::AbstractAdapter</code> where <code>@logger</code> could be <code>nil</code>. You can see that the code uses <code>try</code> and avoids an unnecessary check.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">log_info</span><span class="p">(</span><span class="n">sql</span><span class="p">,</span> <span class="nb">name</span><span class="p">,</span> <span class="n">ms</span><span class="p">)</span> <span class="k">if</span> <span class="vi">@logger</span><span class="p">.</span><span class="nf">try</span><span class="p">(</span><span class="ss">:debug?</span><span class="p">)</span> <span class="nb">name</span> <span class="o">=</span> <span class="s2">"%s (%.1fms)"</span> <span class="o">%</span> <span class="p">[</span><span class="nb">name</span> <span class="o">||</span> <span class="s2">"SQL"</span><span class="p">,</span> <span class="n">ms</span><span class="p">]</span> <span class="vi">@logger</span><span class="p">.</span><span class="nf">debug</span><span class="p">(</span><span class="n">format_log_entry</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">sql</span><span class="p">.</span><span class="nf">squeeze</span><span class="p">(</span><span class="s2">" "</span><span class="p">)))</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def log_info(sql, name, ms) if @logger.try(:debug?) name = "%s (%.1fms)" % [name || "SQL", ms] @logger.debug(format_log_entry(name, sql.squeeze(" "))) end end ">Copy</button> </div> <p><code>try</code> can also be called without arguments but a block, which will only be executed if the object is not nil:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="vi">@person</span><span class="p">.</span><span class="nf">try</span> <span class="p">{</span> <span class="o">|</span><span class="nb">p</span><span class="o">|</span> <span class="s2">"</span><span class="si">#{</span><span class="nb">p</span><span class="p">.</span><span class="nf">first_name</span><span class="si">}</span><span class="s2"> </span><span class="si">#{</span><span class="nb">p</span><span class="p">.</span><span class="nf">last_name</span><span class="si">}</span><span class="s2">"</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="@person.try { |p| "#{p.first_name} #{p.last_name}" } ">Copy</button> </div> <p>Note that <code>try</code> will swallow no-method errors, returning nil instead. If you want to protect against typos, use <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-try-21"><code>try!</code></a> instead:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="vi">@number</span><span class="p">.</span><span class="nf">try</span><span class="p">(</span><span class="ss">:nest</span><span class="p">)</span> <span class="c1"># => nil</span> <span class="vi">@number</span><span class="p">.</span><span class="nf">try!</span><span class="p">(</span><span class="ss">:nest</span><span class="p">)</span> <span class="c1"># NoMethodError: undefined method `nest' for 1:Integer</span> </code></pre> <button class="clipboard-button" data-clipboard-text="@number.try(:nest) # => nil @number.try!(:nest) # NoMethodError: undefined method `nest' for 1:Integer ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/try.rb">active_support/core_ext/object/try.rb</a></code>.</p></div><h3 id="class-eval-args-block"><a class="anchorlink" href="#class-eval-args-block" data-turbo="false"><span>2.6</span> <code>class_eval(*args, &block)</code></a></h3><p>You can evaluate code in the context of any object's singleton class using <a href="https://api.rubyonrails.org/v8.0.0/classes/Kernel.html#method-i-class_eval"><code>class_eval</code></a>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Proc</span> <span class="k">def</span> <span class="nf">bind</span><span class="p">(</span><span class="n">object</span><span class="p">)</span> <span class="n">block</span><span class="p">,</span> <span class="n">time</span> <span class="o">=</span> <span class="nb">self</span><span class="p">,</span> <span class="no">Time</span><span class="p">.</span><span class="nf">current</span> <span class="n">object</span><span class="p">.</span><span class="nf">class_eval</span> <span class="k">do</span> <span class="n">method_name</span> <span class="o">=</span> <span class="s2">"__bind_</span><span class="si">#{</span><span class="n">time</span><span class="p">.</span><span class="nf">to_i</span><span class="si">}</span><span class="s2">_</span><span class="si">#{</span><span class="n">time</span><span class="p">.</span><span class="nf">usec</span><span class="si">}</span><span class="s2">"</span> <span class="n">define_method</span><span class="p">(</span><span class="n">method_name</span><span class="p">,</span> <span class="o">&</span><span class="n">block</span><span class="p">)</span> <span class="nb">method</span> <span class="o">=</span> <span class="nb">instance_method</span><span class="p">(</span><span class="n">method_name</span><span class="p">)</span> <span class="n">remove_method</span><span class="p">(</span><span class="n">method_name</span><span class="p">)</span> <span class="nb">method</span> <span class="k">end</span><span class="p">.</span><span class="nf">bind</span><span class="p">(</span><span class="n">object</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Proc def bind(object) block, time = self, Time.current object.class_eval do method_name = "__bind_#{time.to_i}_#{time.usec}" define_method(method_name, &block) method = instance_method(method_name) remove_method(method_name) method end.bind(object) end end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/kernel/singleton_class.rb">active_support/core_ext/kernel/singleton_class.rb</a></code>.</p></div><h3 id="acts-like-questionmark-duck"><a class="anchorlink" href="#acts-like-questionmark-duck" data-turbo="false"><span>2.7</span> <code>acts_like?(duck)</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-acts_like-3F"><code>acts_like?</code></a> provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as <code>String</code> defines</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">acts_like_string?</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def acts_like_string? end ">Copy</button> </div> <p>which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">some_klass</span><span class="p">.</span><span class="nf">acts_like?</span><span class="p">(</span><span class="ss">:string</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="some_klass.acts_like?(:string) ">Copy</button> </div> <p>Rails has classes that act like <code>Date</code> or <code>Time</code> and follow this contract.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/acts_like.rb">active_support/core_ext/object/acts_like.rb</a></code>.</p></div><h3 id="to-param"><a class="anchorlink" href="#to-param" data-turbo="false"><span>2.8</span> <code>to_param</code></a></h3><p>All objects in Rails respond to the method <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-to_param"><code>to_param</code></a>, which is meant to return something that represents them as values in a query string, or as URL fragments.</p><p>By default <code>to_param</code> just calls <code>to_s</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">7</span><span class="p">.</span><span class="nf">to_param</span> <span class="c1"># => "7"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="7.to_param # => "7" ">Copy</button> </div> <p>The return value of <code>to_param</code> should <strong>not</strong> be escaped:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Tom & Jerry"</span><span class="p">.</span><span class="nf">to_param</span> <span class="c1"># => "Tom & Jerry"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Tom & Jerry".to_param # => "Tom & Jerry" ">Copy</button> </div> <p>Several classes in Rails overwrite this method.</p><p>For example <code>nil</code>, <code>true</code>, and <code>false</code> return themselves. <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-to_param"><code>Array#to_param</code></a> calls <code>to_param</code> on the elements and joins the result with "/":</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="kp">true</span><span class="p">,</span> <span class="no">String</span><span class="p">].</span><span class="nf">to_param</span> <span class="c1"># => "0/true/String"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[0, true, String].to_param # => "0/true/String" ">Copy</button> </div> <p>Notably, the Rails routing system calls <code>to_param</code> on models to get a value for the <code>:id</code> placeholder. <code>ActiveRecord::Base#to_param</code> returns the <code>id</code> of a model, but you can redefine that method in your models. For example, given</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="k">def</span> <span class="nf">to_param</span> <span class="s2">"</span><span class="si">#{</span><span class="nb">id</span><span class="si">}</span><span class="s2">-</span><span class="si">#{</span><span class="nb">name</span><span class="p">.</span><span class="nf">parameterize</span><span class="si">}</span><span class="s2">"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User def to_param "#{id}-#{name.parameterize}" end end ">Copy</button> </div> <p>we get:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span> <span class="c1"># => "/users/357-john-smith"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="user_path(@user) # => "/users/357-john-smith" ">Copy</button> </div> <div class="interstitial warning"><p>Controllers need to be aware of any redefinition of <code>to_param</code> because when a request like that comes in "357-john-smith" is the value of <code>params[:id]</code>.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/to_param.rb">active_support/core_ext/object/to_param.rb</a></code>.</p></div><h3 id="to-query"><a class="anchorlink" href="#to-query" data-turbo="false"><span>2.9</span> <code>to_query</code></a></h3><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-to_query"><code>to_query</code></a> method constructs a query string that associates a given <code>key</code> with the return value of <code>to_param</code>. For example, with the following <code>to_param</code> definition:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="k">def</span> <span class="nf">to_param</span> <span class="s2">"</span><span class="si">#{</span><span class="nb">id</span><span class="si">}</span><span class="s2">-</span><span class="si">#{</span><span class="nb">name</span><span class="p">.</span><span class="nf">parameterize</span><span class="si">}</span><span class="s2">"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User def to_param "#{id}-#{name.parameterize}" end end ">Copy</button> </div> <p>we get:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">current_user</span><span class="p">.</span><span class="nf">to_query</span><span class="p">(</span><span class="s2">"user"</span><span class="p">)</span> <span class="c1"># => "user=357-john-smith"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="current_user.to_query("user") # => "user=357-john-smith" ">Copy</button> </div> <p>This method escapes whatever is needed, both for the key and the value:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">account</span><span class="p">.</span><span class="nf">to_query</span><span class="p">(</span><span class="s2">"company[name]"</span><span class="p">)</span> <span class="c1"># => "company%5Bname%5D=Johnson+%26+Johnson"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="account.to_query("company[name]") # => "company%5Bname%5D=Johnson+%26+Johnson" ">Copy</button> </div> <p>so its output is ready to be used in a query string.</p><p>Arrays return the result of applying <code>to_query</code> to each element with <code>key[]</code> as key, and join the result with "&":</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="mf">3.4</span><span class="p">,</span> <span class="o">-</span><span class="mf">45.6</span><span class="p">].</span><span class="nf">to_query</span><span class="p">(</span><span class="s2">"sample"</span><span class="p">)</span> <span class="c1"># => "sample%5B%5D=3.4&sample%5B%5D=-45.6"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[3.4, -45.6].to_query("sample") # => "sample%5B%5D=3.4&sample%5B%5D=-45.6" ">Copy</button> </div> <p>Hashes also respond to <code>to_query</code> but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling <code>to_query(key)</code> on its values. Then it joins the result with "&":</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">c: </span><span class="mi">3</span><span class="p">,</span> <span class="ss">b: </span><span class="mi">2</span><span class="p">,</span> <span class="ss">a: </span><span class="mi">1</span> <span class="p">}.</span><span class="nf">to_query</span> <span class="c1"># => "a=1&b=2&c=3"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ c: 3, b: 2, a: 1 }.to_query # => "a=1&b=2&c=3" ">Copy</button> </div> <p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-to_query"><code>Hash#to_query</code></a> accepts an optional namespace for the keys:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">id: </span><span class="mi">89</span><span class="p">,</span> <span class="ss">name: </span><span class="s2">"John Smith"</span> <span class="p">}.</span><span class="nf">to_query</span><span class="p">(</span><span class="s2">"user"</span><span class="p">)</span> <span class="c1"># => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ id: 89, name: "John Smith" }.to_query("user") # => "user%5Bid%5D=89&user%5Bname%5D=John+Smith" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/to_query.rb">active_support/core_ext/object/to_query.rb</a></code>.</p></div><h3 id="with-options"><a class="anchorlink" href="#with-options" data-turbo="false"><span>2.10</span> <code>with_options</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-with_options"><code>with_options</code></a> provides a way to factor out common options in a series of method calls.</p><p>Given a default options hash, <code>with_options</code> yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Account</span> <span class="o"><</span> <span class="no">ApplicationRecord</span> <span class="n">has_many</span> <span class="ss">:customers</span><span class="p">,</span> <span class="ss">dependent: :destroy</span> <span class="n">has_many</span> <span class="ss">:products</span><span class="p">,</span> <span class="ss">dependent: :destroy</span> <span class="n">has_many</span> <span class="ss">:invoices</span><span class="p">,</span> <span class="ss">dependent: :destroy</span> <span class="n">has_many</span> <span class="ss">:expenses</span><span class="p">,</span> <span class="ss">dependent: :destroy</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Account < ApplicationRecord has_many :customers, dependent: :destroy has_many :products, dependent: :destroy has_many :invoices, dependent: :destroy has_many :expenses, dependent: :destroy end ">Copy</button> </div> <p>this way:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Account</span> <span class="o"><</span> <span class="no">ApplicationRecord</span> <span class="n">with_options</span> <span class="ss">dependent: :destroy</span> <span class="k">do</span> <span class="o">|</span><span class="n">assoc</span><span class="o">|</span> <span class="n">assoc</span><span class="p">.</span><span class="nf">has_many</span> <span class="ss">:customers</span> <span class="n">assoc</span><span class="p">.</span><span class="nf">has_many</span> <span class="ss">:products</span> <span class="n">assoc</span><span class="p">.</span><span class="nf">has_many</span> <span class="ss">:invoices</span> <span class="n">assoc</span><span class="p">.</span><span class="nf">has_many</span> <span class="ss">:expenses</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Account < ApplicationRecord with_options dependent: :destroy do |assoc| assoc.has_many :customers assoc.has_many :products assoc.has_many :invoices assoc.has_many :expenses end end ">Copy</button> </div> <p>That idiom may convey <em>grouping</em> to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">with_options</span> <span class="ss">locale: </span><span class="n">user</span><span class="p">.</span><span class="nf">locale</span><span class="p">,</span> <span class="ss">scope: </span><span class="s2">"newsletter"</span> <span class="k">do</span> <span class="o">|</span><span class="n">i18n</span><span class="o">|</span> <span class="n">subject</span> <span class="n">i18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:subject</span> <span class="n">body</span> <span class="n">i18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:body</span><span class="p">,</span> <span class="ss">user_name: </span><span class="n">user</span><span class="p">.</span><span class="nf">name</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.with_options locale: user.locale, scope: "newsletter" do |i18n| subject i18n.t :subject body i18n.t :body, user_name: user.name end ">Copy</button> </div> <div class="interstitial info"><p>Since <code>with_options</code> forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/with_options.rb">active_support/core_ext/object/with_options.rb</a></code>.</p></div><h3 id="json-support"><a class="anchorlink" href="#json-support" data-turbo="false"><span>2.11</span> JSON Support</a></h3><p>Active Support provides a better implementation of <code>to_json</code> than the <code>json</code> gem ordinarily provides for Ruby objects. This is because some classes, like <code>Hash</code> and <code>Process::Status</code> need special handling in order to provide a proper JSON representation.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/json.rb">active_support/core_ext/object/json.rb</a></code>.</p></div><h3 id="instance-variables"><a class="anchorlink" href="#instance-variables" data-turbo="false"><span>2.12</span> Instance Variables</a></h3><p>Active Support provides several methods to ease access to instance variables.</p><h4 id="instance-values"><a class="anchorlink" href="#instance-values" data-turbo="false"><span>2.12.1</span> <code>instance_values</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-instance_values"><code>instance_values</code></a> returns a hash that maps instance variable names without "@" to their corresponding values. Keys are strings:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">C</span> <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="vi">@x</span><span class="p">,</span> <span class="vi">@y</span> <span class="o">=</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="k">end</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">).</span><span class="nf">instance_values</span> <span class="c1"># => {"x" => 0, "y" => 1}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class C def initialize(x, y) @x, @y = x, y end end C.new(0, 1).instance_values # => {"x" => 0, "y" => 1} ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/instance_variables.rb">active_support/core_ext/object/instance_variables.rb</a></code>.</p></div><h4 id="instance-variable-names"><a class="anchorlink" href="#instance-variable-names" data-turbo="false"><span>2.12.2</span> <code>instance_variable_names</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-instance_variable_names"><code>instance_variable_names</code></a> returns an array. Each name includes the "@" sign.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">C</span> <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="vi">@x</span><span class="p">,</span> <span class="vi">@y</span> <span class="o">=</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="k">end</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">).</span><span class="nf">instance_variable_names</span> <span class="c1"># => ["@x", "@y"]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class C def initialize(x, y) @x, @y = x, y end end C.new(0, 1).instance_variable_names # => ["@x", "@y"] ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/instance_variables.rb">active_support/core_ext/object/instance_variables.rb</a></code>.</p></div><h3 id="silencing-warnings-and-exceptions"><a class="anchorlink" href="#silencing-warnings-and-exceptions" data-turbo="false"><span>2.13</span> Silencing Warnings and Exceptions</a></h3><p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/Kernel.html#method-i-silence_warnings"><code>silence_warnings</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/Kernel.html#method-i-enable_warnings"><code>enable_warnings</code></a> change the value of <code>$VERBOSE</code> accordingly for the duration of their block, and reset it afterwards:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">silence_warnings</span> <span class="p">{</span> <span class="no">Object</span><span class="p">.</span><span class="nf">const_set</span> <span class="s2">"RAILS_DEFAULT_LOGGER"</span><span class="p">,</span> <span class="n">logger</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger } ">Copy</button> </div> <p>Silencing exceptions is also possible with <a href="https://api.rubyonrails.org/v8.0.0/classes/Kernel.html#method-i-suppress"><code>suppress</code></a>. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is <code>kind_of?</code> any of the arguments, <code>suppress</code> captures it and returns silently. Otherwise the exception is not captured:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># If the user is locked, the increment is lost, no big deal.</span> <span class="n">suppress</span><span class="p">(</span><span class="no">ActiveRecord</span><span class="o">::</span><span class="no">StaleObjectError</span><span class="p">)</span> <span class="k">do</span> <span class="n">current_user</span><span class="p">.</span><span class="nf">increment!</span> <span class="ss">:visits</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# If the user is locked, the increment is lost, no big deal. suppress(ActiveRecord::StaleObjectError) do current_user.increment! :visits end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/kernel/reporting.rb">active_support/core_ext/kernel/reporting.rb</a></code>.</p></div><h3 id="in-questionmark"><a class="anchorlink" href="#in-questionmark" data-turbo="false"><span>2.14</span> <code>in?</code></a></h3><p>The predicate <a href="https://api.rubyonrails.org/v8.0.0/classes/Object.html#method-i-in-3F"><code>in?</code></a> tests if an object is included in another object. An <code>ArgumentError</code> exception will be raised if the argument passed does not respond to <code>include?</code>.</p><p>Examples of <code>in?</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">1</span><span class="p">.</span><span class="nf">in?</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">])</span> <span class="c1"># => true</span> <span class="s2">"lo"</span><span class="p">.</span><span class="nf">in?</span><span class="p">(</span><span class="s2">"hello"</span><span class="p">)</span> <span class="c1"># => true</span> <span class="mi">25</span><span class="p">.</span><span class="nf">in?</span><span class="p">(</span><span class="mi">30</span><span class="o">..</span><span class="mi">50</span><span class="p">)</span> <span class="c1"># => false</span> <span class="mi">1</span><span class="p">.</span><span class="nf">in?</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => ArgumentError</span> </code></pre> <button class="clipboard-button" data-clipboard-text="1.in?([1, 2]) # => true "lo".in?("hello") # => true 25.in?(30..50) # => false 1.in?(1) # => ArgumentError ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/inclusion.rb">active_support/core_ext/object/inclusion.rb</a></code>.</p></div><h2 id="extensions-to-module"><a class="anchorlink" href="#extensions-to-module" data-turbo="false"><span>3</span> Extensions to <code>Module</code></a></h2><h3 id="attributes"><a class="anchorlink" href="#attributes" data-turbo="false"><span>3.1</span> Attributes</a></h3><h4 id="alias-attribute"><a class="anchorlink" href="#alias-attribute" data-turbo="false"><span>3.1.1</span> <code>alias_attribute</code></a></h4><p>Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods all defined for you by using <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-alias_attribute"><code>alias_attribute</code></a>. As in other aliasing methods, the new name is the first argument, and the old name is the second (one mnemonic is that they go in the same order as if you did an assignment):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ApplicationRecord</span> <span class="c1"># You can refer to the email column as "login".</span> <span class="c1"># This can be meaningful for authentication code.</span> <span class="n">alias_attribute</span> <span class="ss">:login</span><span class="p">,</span> <span class="ss">:email</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ApplicationRecord # You can refer to the email column as "login". # This can be meaningful for authentication code. alias_attribute :login, :email end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/aliasing.rb">active_support/core_ext/module/aliasing.rb</a></code>.</p></div><h4 id="internal-attributes"><a class="anchorlink" href="#internal-attributes" data-turbo="false"><span>3.1.2</span> Internal Attributes</a></h4><p>When you are defining an attribute in a class that is meant to be subclassed, name collisions are a risk. That's remarkably important for libraries.</p><p>Active Support defines the macros <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-attr_internal_reader"><code>attr_internal_reader</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-attr_internal_writer"><code>attr_internal_writer</code></a>, and <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-attr_internal_accessor"><code>attr_internal_accessor</code></a>. They behave like their Ruby built-in <code>attr_*</code> counterparts, except they name the underlying instance variable in a way that makes collisions less likely.</p><p>The macro <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-attr_internal"><code>attr_internal</code></a> is a synonym for <code>attr_internal_accessor</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># library</span> <span class="k">class</span> <span class="nc">ThirdPartyLibrary::Crawler</span> <span class="n">attr_internal</span> <span class="ss">:log_level</span> <span class="k">end</span> <span class="c1"># client code</span> <span class="k">class</span> <span class="nc">MyCrawler</span> <span class="o"><</span> <span class="no">ThirdPartyLibrary</span><span class="o">::</span><span class="no">Crawler</span> <span class="nb">attr_accessor</span> <span class="ss">:log_level</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# library class ThirdPartyLibrary::Crawler attr_internal :log_level end # client code class MyCrawler < ThirdPartyLibrary::Crawler attr_accessor :log_level end ">Copy</button> </div> <p>In the previous example it could be the case that <code>:log_level</code> does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own <code>:log_level</code>. Thanks to <code>attr_internal</code> there's no collision.</p><p>By default the internal instance variable is named with a leading underscore, <code>@_log_level</code> in the example above. That's configurable via <code>Module.attr_internal_naming_format</code> though, you can pass any <code>sprintf</code>-like format string with a leading <code>@</code> and a <code>%s</code> somewhere, which is where the name will be placed. The default is <code>"@_%s"</code>.</p><p>Rails uses internal attributes in a few spots, for examples for views:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">ActionView</span> <span class="k">class</span> <span class="nc">Base</span> <span class="n">attr_internal</span> <span class="ss">:captures</span> <span class="n">attr_internal</span> <span class="ss">:request</span><span class="p">,</span> <span class="ss">:layout</span> <span class="n">attr_internal</span> <span class="ss">:controller</span><span class="p">,</span> <span class="ss">:template</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module ActionView class Base attr_internal :captures attr_internal :request, :layout attr_internal :controller, :template end end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/attr_internal.rb">active_support/core_ext/module/attr_internal.rb</a></code>.</p></div><h4 id="module-attributes"><a class="anchorlink" href="#module-attributes" data-turbo="false"><span>3.1.3</span> Module Attributes</a></h4><p>The macros <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-mattr_reader"><code>mattr_reader</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-mattr_writer"><code>mattr_writer</code></a>, and <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-mattr_accessor"><code>mattr_accessor</code></a> are the same as the <code>cattr_*</code> macros defined for class. In fact, the <code>cattr_*</code> macros are just aliases for the <code>mattr_*</code> macros. Check <a href="#class-attributes">Class Attributes</a>.</p><p>For example, the API for the logger of Active Storage is generated with <code>mattr_accessor</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">ActiveStorage</span> <span class="n">mattr_accessor</span> <span class="ss">:logger</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module ActiveStorage mattr_accessor :logger end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb">active_support/core_ext/module/attribute_accessors.rb</a></code>.</p></div><h3 id="parents"><a class="anchorlink" href="#parents" data-turbo="false"><span>3.2</span> Parents</a></h3><h4 id="module-parent"><a class="anchorlink" href="#module-parent" data-turbo="false"><span>3.2.1</span> <code>module_parent</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-module_parent"><code>module_parent</code></a> method on a nested named module returns the module that contains its corresponding constant:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">X</span> <span class="k">module</span> <span class="nn">Y</span> <span class="k">module</span> <span class="nn">Z</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="no">M</span> <span class="o">=</span> <span class="no">X</span><span class="o">::</span><span class="no">Y</span><span class="o">::</span><span class="no">Z</span> <span class="no">X</span><span class="o">::</span><span class="no">Y</span><span class="o">::</span><span class="no">Z</span><span class="p">.</span><span class="nf">module_parent</span> <span class="c1"># => X::Y</span> <span class="no">M</span><span class="p">.</span><span class="nf">module_parent</span> <span class="c1"># => X::Y</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module X module Y module Z end end end M = X::Y::Z X::Y::Z.module_parent # => X::Y M.module_parent # => X::Y ">Copy</button> </div> <p>If the module is anonymous or belongs to the top-level, <code>module_parent</code> returns <code>Object</code>.</p><div class="interstitial warning"><p>Note that in that case <code>module_parent_name</code> returns <code>nil</code>.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/introspection.rb">active_support/core_ext/module/introspection.rb</a></code>.</p></div><h4 id="module-parent-name"><a class="anchorlink" href="#module-parent-name" data-turbo="false"><span>3.2.2</span> <code>module_parent_name</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-module_parent_name"><code>module_parent_name</code></a> method on a nested named module returns the fully qualified name of the module that contains its corresponding constant:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">X</span> <span class="k">module</span> <span class="nn">Y</span> <span class="k">module</span> <span class="nn">Z</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="no">M</span> <span class="o">=</span> <span class="no">X</span><span class="o">::</span><span class="no">Y</span><span class="o">::</span><span class="no">Z</span> <span class="no">X</span><span class="o">::</span><span class="no">Y</span><span class="o">::</span><span class="no">Z</span><span class="p">.</span><span class="nf">module_parent_name</span> <span class="c1"># => "X::Y"</span> <span class="no">M</span><span class="p">.</span><span class="nf">module_parent_name</span> <span class="c1"># => "X::Y"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module X module Y module Z end end end M = X::Y::Z X::Y::Z.module_parent_name # => "X::Y" M.module_parent_name # => "X::Y" ">Copy</button> </div> <p>For top-level or anonymous modules <code>module_parent_name</code> returns <code>nil</code>.</p><div class="interstitial warning"><p>Note that in that case <code>module_parent</code> returns <code>Object</code>.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/introspection.rb">active_support/core_ext/module/introspection.rb</a></code>.</p></div><h4 id="module-parents"><a class="anchorlink" href="#module-parents" data-turbo="false"><span>3.2.3</span> <code>module_parents</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-module_parents"><code>module_parents</code></a> calls <code>module_parent</code> on the receiver and upwards until <code>Object</code> is reached. The chain is returned in an array, from bottom to top:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">X</span> <span class="k">module</span> <span class="nn">Y</span> <span class="k">module</span> <span class="nn">Z</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="no">M</span> <span class="o">=</span> <span class="no">X</span><span class="o">::</span><span class="no">Y</span><span class="o">::</span><span class="no">Z</span> <span class="no">X</span><span class="o">::</span><span class="no">Y</span><span class="o">::</span><span class="no">Z</span><span class="p">.</span><span class="nf">module_parents</span> <span class="c1"># => [X::Y, X, Object]</span> <span class="no">M</span><span class="p">.</span><span class="nf">module_parents</span> <span class="c1"># => [X::Y, X, Object]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module X module Y module Z end end end M = X::Y::Z X::Y::Z.module_parents # => [X::Y, X, Object] M.module_parents # => [X::Y, X, Object] ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/introspection.rb">active_support/core_ext/module/introspection.rb</a></code>.</p></div><h3 id="anonymous"><a class="anchorlink" href="#anonymous" data-turbo="false"><span>3.3</span> Anonymous</a></h3><p>A module may or may not have a name:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">M</span> <span class="k">end</span> <span class="no">M</span><span class="p">.</span><span class="nf">name</span> <span class="c1"># => "M"</span> <span class="no">N</span> <span class="o">=</span> <span class="no">Module</span><span class="p">.</span><span class="nf">new</span> <span class="no">N</span><span class="p">.</span><span class="nf">name</span> <span class="c1"># => "N"</span> <span class="no">Module</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">name</span> <span class="c1"># => nil</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module M end M.name # => "M" N = Module.new N.name # => "N" Module.new.name # => nil ">Copy</button> </div> <p>You can check whether a module has a name with the predicate <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-anonymous-3F"><code>anonymous?</code></a>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">M</span> <span class="k">end</span> <span class="no">M</span><span class="p">.</span><span class="nf">anonymous?</span> <span class="c1"># => false</span> <span class="no">Module</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">anonymous?</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module M end M.anonymous? # => false Module.new.anonymous? # => true ">Copy</button> </div> <p>Note that being unreachable does not imply being anonymous:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">M</span> <span class="k">end</span> <span class="n">m</span> <span class="o">=</span> <span class="no">Object</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="ss">:remove_const</span><span class="p">,</span> <span class="ss">:M</span><span class="p">)</span> <span class="n">m</span><span class="p">.</span><span class="nf">anonymous?</span> <span class="c1"># => false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module M end m = Object.send(:remove_const, :M) m.anonymous? # => false ">Copy</button> </div> <p>though an anonymous module is unreachable by definition.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/anonymous.rb">active_support/core_ext/module/anonymous.rb</a></code>.</p></div><h3 id="method-delegation"><a class="anchorlink" href="#method-delegation" data-turbo="false"><span>3.4</span> Method Delegation</a></h3><h4 id="delegate"><a class="anchorlink" href="#delegate" data-turbo="false"><span>3.4.1</span> <code>delegate</code></a></h4><p>The macro <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-delegate"><code>delegate</code></a> offers an easy way to forward methods.</p><p>Let's imagine that users in some application have login information in the <code>User</code> model but name and other data in a separate <code>Profile</code> model:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ApplicationRecord</span> <span class="n">has_one</span> <span class="ss">:profile</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ApplicationRecord has_one :profile end ">Copy</button> </div> <p>With that configuration you get a user's name via their profile, <code>user.profile.name</code>, but it could be handy to still be able to access such attribute directly:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ApplicationRecord</span> <span class="n">has_one</span> <span class="ss">:profile</span> <span class="k">def</span> <span class="nf">name</span> <span class="n">profile</span><span class="p">.</span><span class="nf">name</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ApplicationRecord has_one :profile def name profile.name end end ">Copy</button> </div> <p>That is what <code>delegate</code> does for you:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ApplicationRecord</span> <span class="n">has_one</span> <span class="ss">:profile</span> <span class="n">delegate</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">to: :profile</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ApplicationRecord has_one :profile delegate :name, to: :profile end ">Copy</button> </div> <p>It is shorter, and the intention more obvious.</p><p>The method must be public in the target.</p><p>The <code>delegate</code> macro accepts several methods:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">delegate</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">:age</span><span class="p">,</span> <span class="ss">:address</span><span class="p">,</span> <span class="ss">:twitter</span><span class="p">,</span> <span class="ss">to: :profile</span> </code></pre> <button class="clipboard-button" data-clipboard-text="delegate :name, :age, :address, :twitter, to: :profile ">Copy</button> </div> <p>When interpolated into a string, the <code>:to</code> option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># delegates to the Rails constant</span> <span class="n">delegate</span> <span class="ss">:logger</span><span class="p">,</span> <span class="ss">to: :Rails</span> <span class="c1"># delegates to the receiver's class</span> <span class="n">delegate</span> <span class="ss">:table_name</span><span class="p">,</span> <span class="ss">to: :class</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# delegates to the Rails constant delegate :logger, to: :Rails # delegates to the receiver's class delegate :table_name, to: :class ">Copy</button> </div> <div class="interstitial warning"><p>If the <code>:prefix</code> option is <code>true</code> this is less generic, see below.</p></div><p>By default, if the delegation raises <code>NoMethodError</code> and the target is <code>nil</code> the exception is propagated. You can ask that <code>nil</code> is returned instead with the <code>:allow_nil</code> option:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">delegate</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">to: :profile</span><span class="p">,</span> <span class="ss">allow_nil: </span><span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="delegate :name, to: :profile, allow_nil: true ">Copy</button> </div> <p>With <code>:allow_nil</code> the call <code>user.name</code> returns <code>nil</code> if the user has no profile.</p><p>The option <code>:prefix</code> adds a prefix to the name of the generated method. This may be handy for example to get a better name:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">delegate</span> <span class="ss">:street</span><span class="p">,</span> <span class="ss">to: :address</span><span class="p">,</span> <span class="ss">prefix: </span><span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="delegate :street, to: :address, prefix: true ">Copy</button> </div> <p>The previous example generates <code>address_street</code> rather than <code>street</code>.</p><div class="interstitial warning"><p>Since in this case the name of the generated method is composed of the target object and target method names, the <code>:to</code> option must be a method name.</p></div><p>A custom prefix may also be configured:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">delegate</span> <span class="ss">:size</span><span class="p">,</span> <span class="ss">to: :attachment</span><span class="p">,</span> <span class="ss">prefix: :avatar</span> </code></pre> <button class="clipboard-button" data-clipboard-text="delegate :size, to: :attachment, prefix: :avatar ">Copy</button> </div> <p>In the previous example the macro generates <code>avatar_size</code> rather than <code>size</code>.</p><p>The option <code>:private</code> changes methods scope:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">delegate</span> <span class="ss">:date_of_birth</span><span class="p">,</span> <span class="ss">to: :profile</span><span class="p">,</span> <span class="ss">private: </span><span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="delegate :date_of_birth, to: :profile, private: true ">Copy</button> </div> <p>The delegated methods are public by default. Pass <code>private: true</code> to change that.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/delegation.rb">active_support/core_ext/module/delegation.rb</a></code>.</p></div><h4 id="delegate-missing-to"><a class="anchorlink" href="#delegate-missing-to" data-turbo="false"><span>3.4.2</span> <code>delegate_missing_to</code></a></h4><p>Imagine you would like to delegate everything missing from the <code>User</code> object, to the <code>Profile</code> one. The <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-delegate_missing_to"><code>delegate_missing_to</code></a> macro lets you implement this in a breeze:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ApplicationRecord</span> <span class="n">has_one</span> <span class="ss">:profile</span> <span class="n">delegate_missing_to</span> <span class="ss">:profile</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ApplicationRecord has_one :profile delegate_missing_to :profile end ">Copy</button> </div> <p>The target can be anything callable within the object, e.g. instance variables, methods, constants, etc. Only the public methods of the target are delegated.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/delegation.rb">active_support/core_ext/module/delegation.rb</a></code>.</p></div><h3 id="redefining-methods"><a class="anchorlink" href="#redefining-methods" data-turbo="false"><span>3.5</span> Redefining Methods</a></h3><p>There are cases where you need to define a method with <code>define_method</code>, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.</p><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-redefine_method"><code>redefine_method</code></a> prevents such a potential warning, removing the existing method before if needed.</p><p>You can also use <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-silence_redefinition_of_method"><code>silence_redefinition_of_method</code></a> if you need to define the replacement method yourself (because you're using <code>delegate</code>, for example).</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/redefine_method.rb">active_support/core_ext/module/redefine_method.rb</a></code>.</p></div><h2 id="extensions-to-class"><a class="anchorlink" href="#extensions-to-class" data-turbo="false"><span>4</span> Extensions to <code>Class</code></a></h2><h3 id="class-attributes"><a class="anchorlink" href="#class-attributes" data-turbo="false"><span>4.1</span> Class Attributes</a></h3><h4 id="class-attribute"><a class="anchorlink" href="#class-attribute" data-turbo="false"><span>4.1.1</span> <code>class_attribute</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Class.html#method-i-class_attribute"><code>class_attribute</code></a> declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">A</span> <span class="n">class_attribute</span> <span class="ss">:x</span> <span class="k">end</span> <span class="k">class</span> <span class="nc">B</span> <span class="o"><</span> <span class="no">A</span><span class="p">;</span> <span class="k">end</span> <span class="k">class</span> <span class="nc">C</span> <span class="o"><</span> <span class="no">B</span><span class="p">;</span> <span class="k">end</span> <span class="no">A</span><span class="p">.</span><span class="nf">x</span> <span class="o">=</span> <span class="ss">:a</span> <span class="no">B</span><span class="p">.</span><span class="nf">x</span> <span class="c1"># => :a</span> <span class="no">C</span><span class="p">.</span><span class="nf">x</span> <span class="c1"># => :a</span> <span class="no">B</span><span class="p">.</span><span class="nf">x</span> <span class="o">=</span> <span class="ss">:b</span> <span class="no">A</span><span class="p">.</span><span class="nf">x</span> <span class="c1"># => :a</span> <span class="no">C</span><span class="p">.</span><span class="nf">x</span> <span class="c1"># => :b</span> <span class="no">C</span><span class="p">.</span><span class="nf">x</span> <span class="o">=</span> <span class="ss">:c</span> <span class="no">A</span><span class="p">.</span><span class="nf">x</span> <span class="c1"># => :a</span> <span class="no">B</span><span class="p">.</span><span class="nf">x</span> <span class="c1"># => :b</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class A class_attribute :x end class B < A; end class C < B; end A.x = :a B.x # => :a C.x # => :a B.x = :b A.x # => :a C.x # => :b C.x = :c A.x # => :a B.x # => :b ">Copy</button> </div> <p>For example <code>ActionMailer::Base</code> defines:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">class_attribute</span> <span class="ss">:default_params</span> <span class="nb">self</span><span class="p">.</span><span class="nf">default_params</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">mime_version: </span><span class="s2">"1.0"</span><span class="p">,</span> <span class="ss">charset: </span><span class="s2">"UTF-8"</span><span class="p">,</span> <span class="ss">content_type: </span><span class="s2">"text/plain"</span><span class="p">,</span> <span class="ss">parts_order: </span><span class="p">[</span> <span class="s2">"text/plain"</span><span class="p">,</span> <span class="s2">"text/enriched"</span><span class="p">,</span> <span class="s2">"text/html"</span> <span class="p">]</span> <span class="p">}.</span><span class="nf">freeze</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class_attribute :default_params self.default_params = { mime_version: "1.0", charset: "UTF-8", content_type: "text/plain", parts_order: [ "text/plain", "text/enriched", "text/html" ] }.freeze ">Copy</button> </div> <p>They can also be accessed and overridden at the instance level.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">A</span><span class="p">.</span><span class="nf">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="n">a1</span> <span class="o">=</span> <span class="no">A</span><span class="p">.</span><span class="nf">new</span> <span class="n">a2</span> <span class="o">=</span> <span class="no">A</span><span class="p">.</span><span class="nf">new</span> <span class="n">a2</span><span class="p">.</span><span class="nf">x</span> <span class="o">=</span> <span class="mi">2</span> <span class="n">a1</span><span class="p">.</span><span class="nf">x</span> <span class="c1"># => 1, comes from A</span> <span class="n">a2</span><span class="p">.</span><span class="nf">x</span> <span class="c1"># => 2, overridden in a2</span> </code></pre> <button class="clipboard-button" data-clipboard-text="A.x = 1 a1 = A.new a2 = A.new a2.x = 2 a1.x # => 1, comes from A a2.x # => 2, overridden in a2 ">Copy</button> </div> <p>The generation of the writer instance method can be prevented by setting the option <code>:instance_writer</code> to <code>false</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">ActiveRecord</span> <span class="k">class</span> <span class="nc">Base</span> <span class="n">class_attribute</span> <span class="ss">:table_name_prefix</span><span class="p">,</span> <span class="ss">instance_writer: </span><span class="kp">false</span><span class="p">,</span> <span class="ss">default: </span><span class="s2">"my"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module ActiveRecord class Base class_attribute :table_name_prefix, instance_writer: false, default: "my" end end ">Copy</button> </div> <p>A model may find that option useful as a way to prevent mass-assignment from setting the attribute.</p><p>The generation of the reader instance method can be prevented by setting the option <code>:instance_reader</code> to <code>false</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">A</span> <span class="n">class_attribute</span> <span class="ss">:x</span><span class="p">,</span> <span class="ss">instance_reader: </span><span class="kp">false</span> <span class="k">end</span> <span class="no">A</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="no">A</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">x</span> <span class="c1"># NoMethodError</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class A class_attribute :x, instance_reader: false end A.new.x = 1 A.new.x # NoMethodError ">Copy</button> </div> <p>For convenience <code>class_attribute</code> also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called <code>x?</code>.</p><p>When <code>:instance_reader</code> is <code>false</code>, the instance predicate returns a <code>NoMethodError</code> just like the reader method.</p><p>If you do not want the instance predicate, pass <code>instance_predicate: false</code> and it will not be defined.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/class/attribute.rb">active_support/core_ext/class/attribute.rb</a></code>.</p></div><h4 id="cattr-reader-cattr-writer-and-cattr-accessor"><a class="anchorlink" href="#cattr-reader-cattr-writer-and-cattr-accessor" data-turbo="false"><span>4.1.2</span> <code>cattr_reader</code>, <code>cattr_writer</code>, and <code>cattr_accessor</code></a></h4><p>The macros <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-cattr_reader"><code>cattr_reader</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-cattr_writer"><code>cattr_writer</code></a>, and <a href="https://api.rubyonrails.org/v8.0.0/classes/Module.html#method-i-cattr_accessor"><code>cattr_accessor</code></a> are analogous to their <code>attr_*</code> counterparts but for classes. They initialize a class variable to <code>nil</code> unless it already exists, and generate the corresponding class methods to access it:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">MysqlAdapter</span> <span class="o"><</span> <span class="no">AbstractAdapter</span> <span class="c1"># Generates class methods to access @@emulate_booleans.</span> <span class="n">cattr_accessor</span> <span class="ss">:emulate_booleans</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class MysqlAdapter < AbstractAdapter # Generates class methods to access @@emulate_booleans. cattr_accessor :emulate_booleans end ">Copy</button> </div> <p>Also, you can pass a block to <code>cattr_*</code> to set up the attribute with a default value:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">MysqlAdapter</span> <span class="o"><</span> <span class="no">AbstractAdapter</span> <span class="c1"># Generates class methods to access @@emulate_booleans with default value of true.</span> <span class="n">cattr_accessor</span> <span class="ss">:emulate_booleans</span><span class="p">,</span> <span class="ss">default: </span><span class="kp">true</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class MysqlAdapter < AbstractAdapter # Generates class methods to access @@emulate_booleans with default value of true. cattr_accessor :emulate_booleans, default: true end ">Copy</button> </div> <p>Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with <code>class_attribute</code> (see above). For example given</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">ActionView</span> <span class="k">class</span> <span class="nc">Base</span> <span class="n">cattr_accessor</span> <span class="ss">:field_error_proc</span><span class="p">,</span> <span class="ss">default: </span><span class="no">Proc</span><span class="p">.</span><span class="nf">new</span> <span class="p">{</span> <span class="c1"># ...</span> <span class="p">}</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module ActionView class Base cattr_accessor :field_error_proc, default: Proc.new { # ... } end end ">Copy</button> </div> <p>we can access <code>field_error_proc</code> in views.</p><p>The generation of the reader instance method can be prevented by setting <code>:instance_reader</code> to <code>false</code> and the generation of the writer instance method can be prevented by setting <code>:instance_writer</code> to <code>false</code>. Generation of both methods can be prevented by setting <code>:instance_accessor</code> to <code>false</code>. In all cases, the value must be exactly <code>false</code> and not any false value.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">A</span> <span class="k">class</span> <span class="nc">B</span> <span class="c1"># No first_name instance reader is generated.</span> <span class="n">cattr_accessor</span> <span class="ss">:first_name</span><span class="p">,</span> <span class="ss">instance_reader: </span><span class="kp">false</span> <span class="c1"># No last_name= instance writer is generated.</span> <span class="n">cattr_accessor</span> <span class="ss">:last_name</span><span class="p">,</span> <span class="ss">instance_writer: </span><span class="kp">false</span> <span class="c1"># No surname instance reader or surname= writer is generated.</span> <span class="n">cattr_accessor</span> <span class="ss">:surname</span><span class="p">,</span> <span class="ss">instance_accessor: </span><span class="kp">false</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module A class B # No first_name instance reader is generated. cattr_accessor :first_name, instance_reader: false # No last_name= instance writer is generated. cattr_accessor :last_name, instance_writer: false # No surname instance reader or surname= writer is generated. cattr_accessor :surname, instance_accessor: false end end ">Copy</button> </div> <p>A model may find it useful to set <code>:instance_accessor</code> to <code>false</code> as a way to prevent mass-assignment from setting the attribute.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb">active_support/core_ext/module/attribute_accessors.rb</a></code>.</p></div><h3 id="subclasses-and-descendants"><a class="anchorlink" href="#subclasses-and-descendants" data-turbo="false"><span>4.2</span> Subclasses and Descendants</a></h3><h4 id="subclasses"><a class="anchorlink" href="#subclasses" data-turbo="false"><span>4.2.1</span> <code>subclasses</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/Class.html#method-i-subclasses"><code>subclasses</code></a> method returns the subclasses of the receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">C</span><span class="p">;</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">subclasses</span> <span class="c1"># => []</span> <span class="k">class</span> <span class="nc">B</span> <span class="o"><</span> <span class="no">C</span><span class="p">;</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">subclasses</span> <span class="c1"># => [B]</span> <span class="k">class</span> <span class="nc">A</span> <span class="o"><</span> <span class="no">B</span><span class="p">;</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">subclasses</span> <span class="c1"># => [B]</span> <span class="k">class</span> <span class="nc">D</span> <span class="o"><</span> <span class="no">C</span><span class="p">;</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">subclasses</span> <span class="c1"># => [B, D]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class C; end C.subclasses # => [] class B < C; end C.subclasses # => [B] class A < B; end C.subclasses # => [B] class D < C; end C.subclasses # => [B, D] ">Copy</button> </div> <p>The order in which these classes are returned is unspecified.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/class/subclasses.rb">active_support/core_ext/class/subclasses.rb</a></code>.</p></div><h4 id="descendants"><a class="anchorlink" href="#descendants" data-turbo="false"><span>4.2.2</span> <code>descendants</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/Class.html#method-i-descendants"><code>descendants</code></a> method returns all classes that are <code><</code> than its receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">C</span><span class="p">;</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">descendants</span> <span class="c1"># => []</span> <span class="k">class</span> <span class="nc">B</span> <span class="o"><</span> <span class="no">C</span><span class="p">;</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">descendants</span> <span class="c1"># => [B]</span> <span class="k">class</span> <span class="nc">A</span> <span class="o"><</span> <span class="no">B</span><span class="p">;</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">descendants</span> <span class="c1"># => [B, A]</span> <span class="k">class</span> <span class="nc">D</span> <span class="o"><</span> <span class="no">C</span><span class="p">;</span> <span class="k">end</span> <span class="no">C</span><span class="p">.</span><span class="nf">descendants</span> <span class="c1"># => [B, A, D]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class C; end C.descendants # => [] class B < C; end C.descendants # => [B] class A < B; end C.descendants # => [B, A] class D < C; end C.descendants # => [B, A, D] ">Copy</button> </div> <p>The order in which these classes are returned is unspecified.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/class/subclasses.rb">active_support/core_ext/class/subclasses.rb</a></code>.</p></div><h2 id="extensions-to-string"><a class="anchorlink" href="#extensions-to-string" data-turbo="false"><span>5</span> Extensions to <code>String</code></a></h2><h3 id="output-safety"><a class="anchorlink" href="#output-safety" data-turbo="false"><span>5.1</span> Output Safety</a></h3><h4 id="motivation"><a class="anchorlink" href="#motivation" data-turbo="false"><span>5.1.1</span> Motivation</a></h4><p>Inserting data into HTML templates needs extra care. For example, you can't just interpolate <code>@review.title</code> verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the section about cross-site scripting in the <a href="security.html#cross-site-scripting-xss">Security guide</a> for further information about the risks.</p><h4 id="safe-strings"><a class="anchorlink" href="#safe-strings" data-turbo="false"><span>5.1.2</span> Safe Strings</a></h4><p>Active Support has the concept of <em>(html) safe</em> strings. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.</p><p>Strings are considered to be <em>unsafe</em> by default:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">""</span><span class="p">.</span><span class="nf">html_safe?</span> <span class="c1"># => false</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""".html_safe? # => false ">Copy</button> </div> <p>You can obtain a safe string from a given one with the <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-html_safe"><code>html_safe</code></a> method:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">s</span> <span class="o">=</span> <span class="s2">""</span><span class="p">.</span><span class="nf">html_safe</span> <span class="n">s</span><span class="p">.</span><span class="nf">html_safe?</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="s = "".html_safe s.html_safe? # => true ">Copy</button> </div> <p>It is important to understand that <code>html_safe</code> performs no escaping whatsoever, it is just an assertion:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">s</span> <span class="o">=</span> <span class="s2">"<script>...</script>"</span><span class="p">.</span><span class="nf">html_safe</span> <span class="n">s</span><span class="p">.</span><span class="nf">html_safe?</span> <span class="c1"># => true</span> <span class="n">s</span> <span class="c1"># => "<script>...</script>"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="s = "<script>...</script>".html_safe s.html_safe? # => true s # => "<script>...</script>" ">Copy</button> </div> <p>It is your responsibility to ensure calling <code>html_safe</code> on a particular string is fine.</p><p>If you append onto a safe string, either in-place with <code>concat</code>/<code><<</code>, or with <code>+</code>, the result is a safe string. Unsafe arguments are escaped:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">""</span><span class="p">.</span><span class="nf">html_safe</span> <span class="o">+</span> <span class="s2">"<"</span> <span class="c1"># => "&lt;"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""".html_safe + "<" # => "&lt;" ">Copy</button> </div> <p>Safe arguments are directly appended:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">""</span><span class="p">.</span><span class="nf">html_safe</span> <span class="o">+</span> <span class="s2">"<"</span><span class="p">.</span><span class="nf">html_safe</span> <span class="c1"># => "<"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""".html_safe + "<".html_safe # => "<" ">Copy</button> </div> <p>These methods should not be used in ordinary views. Unsafe values are automatically escaped:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp"><%=</span> <span class="vi">@review</span><span class="p">.</span><span class="nf">title</span> <span class="cp">%></span> <span class="c"><%# fine, escaped if needed %></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= @review.title %> <%# fine, escaped if needed %> ">Copy</button> </div> <p>To insert something verbatim use the <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/OutputSafetyHelper.html#method-i-raw"><code>raw</code></a> helper rather than calling <code>html_safe</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp"><%=</span> <span class="n">raw</span> <span class="vi">@cms</span><span class="p">.</span><span class="nf">current_template</span> <span class="cp">%></span> <span class="c"><%# inserts @cms.current_template as is %></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %> ">Copy</button> </div> <p>or, equivalently, use <code><%==</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp"><%=</span><span class="o">=</span> <span class="vi">@cms</span><span class="p">.</span><span class="nf">current_template</span> <span class="cp">%></span> <span class="c"><%# inserts @cms.current_template as is %></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%== @cms.current_template %> <%# inserts @cms.current_template as is %> ">Copy</button> </div> <p>The <code>raw</code> helper calls <code>html_safe</code> for you:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">raw</span><span class="p">(</span><span class="n">stringish</span><span class="p">)</span> <span class="n">stringish</span><span class="p">.</span><span class="nf">to_s</span><span class="p">.</span><span class="nf">html_safe</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def raw(stringish) stringish.to_s.html_safe end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/output_safety.rb">active_support/core_ext/string/output_safety.rb</a></code>.</p></div><h4 id="transformation"><a class="anchorlink" href="#transformation" data-turbo="false"><span>5.1.3</span> Transformation</a></h4><p>As a rule of thumb, except perhaps for concatenation as explained above, any method that may change a string gives you an unsafe string. These are <code>downcase</code>, <code>gsub</code>, <code>strip</code>, <code>chomp</code>, <code>underscore</code>, etc.</p><p>In the case of in-place transformations like <code>gsub!</code> the receiver itself becomes unsafe.</p><div class="interstitial info"><p>The safety bit is lost always, no matter whether the transformation actually changed something.</p></div><h4 id="conversion-and-coercion"><a class="anchorlink" href="#conversion-and-coercion" data-turbo="false"><span>5.1.4</span> Conversion and Coercion</a></h4><p>Calling <code>to_s</code> on a safe string returns a safe string, but coercion with <code>to_str</code> returns an unsafe string.</p><h4 id="copying"><a class="anchorlink" href="#copying" data-turbo="false"><span>5.1.5</span> Copying</a></h4><p>Calling <code>dup</code> or <code>clone</code> on safe strings yields safe strings.</p><h3 id="remove"><a class="anchorlink" href="#remove" data-turbo="false"><span>5.2</span> <code>remove</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-remove"><code>remove</code></a> will remove all occurrences of the pattern:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Hello World"</span><span class="p">.</span><span class="nf">remove</span><span class="p">(</span><span class="sr">/Hello /</span><span class="p">)</span> <span class="c1"># => "World"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Hello World".remove(/Hello /) # => "World" ">Copy</button> </div> <p>There's also the destructive version <code>String#remove!</code>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/filters.rb">active_support/core_ext/string/filters.rb</a></code>.</p></div><h3 id="squish"><a class="anchorlink" href="#squish" data-turbo="false"><span>5.3</span> <code>squish</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-squish"><code>squish</code></a> strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">" </span><span class="se">\n</span><span class="s2"> foo</span><span class="se">\n\r</span><span class="s2"> </span><span class="se">\t</span><span class="s2"> bar </span><span class="se">\n</span><span class="s2">"</span><span class="p">.</span><span class="nf">squish</span> <span class="c1"># => "foo bar"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="" \n foo\n\r \t bar \n".squish # => "foo bar" ">Copy</button> </div> <p>There's also the destructive version <code>String#squish!</code>.</p><p>Note that it handles both ASCII and Unicode whitespace.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/filters.rb">active_support/core_ext/string/filters.rb</a></code>.</p></div><h3 id="truncate"><a class="anchorlink" href="#truncate" data-turbo="false"><span>5.4</span> <code>truncate</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-truncate"><code>truncate</code></a> returns a copy of its receiver truncated after a given <code>length</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Oh dear! Oh dear! I shall be late!"</span><span class="p">.</span><span class="nf">truncate</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span> <span class="c1"># => "Oh dear! Oh dear!..."</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Oh dear! Oh dear! I shall be late!".truncate(20) # => "Oh dear! Oh dear!..." ">Copy</button> </div> <p>Ellipsis can be customized with the <code>:omission</code> option:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Oh dear! Oh dear! I shall be late!"</span><span class="p">.</span><span class="nf">truncate</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span> <span class="ss">omission: </span><span class="s2">"&hellip;"</span><span class="p">)</span> <span class="c1"># => "Oh dear! Oh &hellip;"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Oh dear! Oh dear! I shall be late!".truncate(20, omission: "&hellip;") # => "Oh dear! Oh &hellip;" ">Copy</button> </div> <p>Note in particular that truncation takes into account the length of the omission string.</p><p>Pass a <code>:separator</code> to truncate the string at a natural break:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Oh dear! Oh dear! I shall be late!"</span><span class="p">.</span><span class="nf">truncate</span><span class="p">(</span><span class="mi">18</span><span class="p">)</span> <span class="c1"># => "Oh dear! Oh dea..."</span> <span class="s2">"Oh dear! Oh dear! I shall be late!"</span><span class="p">.</span><span class="nf">truncate</span><span class="p">(</span><span class="mi">18</span><span class="p">,</span> <span class="ss">separator: </span><span class="s2">" "</span><span class="p">)</span> <span class="c1"># => "Oh dear! Oh..."</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Oh dear! Oh dear! I shall be late!".truncate(18) # => "Oh dear! Oh dea..." "Oh dear! Oh dear! I shall be late!".truncate(18, separator: " ") # => "Oh dear! Oh..." ">Copy</button> </div> <p>The option <code>:separator</code> can be a regexp:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Oh dear! Oh dear! I shall be late!"</span><span class="p">.</span><span class="nf">truncate</span><span class="p">(</span><span class="mi">18</span><span class="p">,</span> <span class="ss">separator: </span><span class="sr">/\s/</span><span class="p">)</span> <span class="c1"># => "Oh dear! Oh..."</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Oh dear! Oh dear! I shall be late!".truncate(18, separator: /\s/) # => "Oh dear! Oh..." ">Copy</button> </div> <p>In above examples "dear" gets cut first, but then <code>:separator</code> prevents it.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/filters.rb">active_support/core_ext/string/filters.rb</a></code>.</p></div><h3 id="truncate-bytes"><a class="anchorlink" href="#truncate-bytes" data-turbo="false"><span>5.5</span> <code>truncate_bytes</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-truncate_bytes"><code>truncate_bytes</code></a> returns a copy of its receiver truncated to at most <code>bytesize</code> bytes:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"👍👍👍👍"</span><span class="p">.</span><span class="nf">truncate_bytes</span><span class="p">(</span><span class="mi">15</span><span class="p">)</span> <span class="c1"># => "👍👍👍…"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""👍👍👍👍".truncate_bytes(15) # => "👍👍👍…" ">Copy</button> </div> <p>Ellipsis can be customized with the <code>:omission</code> option:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"👍👍👍👍"</span><span class="p">.</span><span class="nf">truncate_bytes</span><span class="p">(</span><span class="mi">15</span><span class="p">,</span> <span class="ss">omission: </span><span class="s2">"🖖"</span><span class="p">)</span> <span class="c1"># => "👍👍🖖"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""👍👍👍👍".truncate_bytes(15, omission: "🖖") # => "👍👍🖖" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/filters.rb">active_support/core_ext/string/filters.rb</a></code>.</p></div><h3 id="truncate-words"><a class="anchorlink" href="#truncate-words" data-turbo="false"><span>5.6</span> <code>truncate_words</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-truncate_words"><code>truncate_words</code></a> returns a copy of its receiver truncated after a given number of words:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Oh dear! Oh dear! I shall be late!"</span><span class="p">.</span><span class="nf">truncate_words</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="c1"># => "Oh dear! Oh dear!..."</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Oh dear! Oh dear! I shall be late!".truncate_words(4) # => "Oh dear! Oh dear!..." ">Copy</button> </div> <p>Ellipsis can be customized with the <code>:omission</code> option:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Oh dear! Oh dear! I shall be late!"</span><span class="p">.</span><span class="nf">truncate_words</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="ss">omission: </span><span class="s2">"&hellip;"</span><span class="p">)</span> <span class="c1"># => "Oh dear! Oh dear!&hellip;"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Oh dear! Oh dear! I shall be late!".truncate_words(4, omission: "&hellip;") # => "Oh dear! Oh dear!&hellip;" ">Copy</button> </div> <p>Pass a <code>:separator</code> to truncate the string at a natural break:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Oh dear! Oh dear! I shall be late!"</span><span class="p">.</span><span class="nf">truncate_words</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="ss">separator: </span><span class="s2">"!"</span><span class="p">)</span> <span class="c1"># => "Oh dear! Oh dear! I shall be late..."</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Oh dear! Oh dear! I shall be late!".truncate_words(3, separator: "!") # => "Oh dear! Oh dear! I shall be late..." ">Copy</button> </div> <p>The option <code>:separator</code> can be a regexp:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Oh dear! Oh dear! I shall be late!"</span><span class="p">.</span><span class="nf">truncate_words</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="ss">separator: </span><span class="sr">/\s/</span><span class="p">)</span> <span class="c1"># => "Oh dear! Oh dear!..."</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Oh dear! Oh dear! I shall be late!".truncate_words(4, separator: /\s/) # => "Oh dear! Oh dear!..." ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/filters.rb">active_support/core_ext/string/filters.rb</a></code>.</p></div><h3 id="inquiry"><a class="anchorlink" href="#inquiry" data-turbo="false"><span>5.7</span> <code>inquiry</code></a></h3><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-inquiry"><code>inquiry</code></a> method converts a string into a <code>StringInquirer</code> object making equality checks prettier.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"production"</span><span class="p">.</span><span class="nf">inquiry</span><span class="p">.</span><span class="nf">production?</span> <span class="c1"># => true</span> <span class="s2">"active"</span><span class="p">.</span><span class="nf">inquiry</span><span class="p">.</span><span class="nf">inactive?</span> <span class="c1"># => false</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""production".inquiry.production? # => true "active".inquiry.inactive? # => false ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inquiry.rb">active_support/core_ext/string/inquiry.rb</a></code>.</p></div><h3 id="extensions-to-string-starts-with-questionmark-and-ends-with-questionmark"><a class="anchorlink" href="#extensions-to-string-starts-with-questionmark-and-ends-with-questionmark" data-turbo="false"><span>5.8</span> <code>starts_with?</code> and <code>ends_with?</code></a></h3><p>Active Support defines 3rd person aliases of <code>String#start_with?</code> and <code>String#end_with?</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"foo"</span><span class="p">.</span><span class="nf">starts_with?</span><span class="p">(</span><span class="s2">"f"</span><span class="p">)</span> <span class="c1"># => true</span> <span class="s2">"foo"</span><span class="p">.</span><span class="nf">ends_with?</span><span class="p">(</span><span class="s2">"o"</span><span class="p">)</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""foo".starts_with?("f") # => true "foo".ends_with?("o") # => true ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb">active_support/core_ext/string/starts_ends_with.rb</a></code>.</p></div><h3 id="strip-heredoc"><a class="anchorlink" href="#strip-heredoc" data-turbo="false"><span>5.9</span> <code>strip_heredoc</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-strip_heredoc"><code>strip_heredoc</code></a> strips indentation in heredocs.</p><p>For example in</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:usage</span><span class="p">]</span> <span class="nb">puts</span> <span class="o"><<-</span><span class="no">USAGE</span><span class="p">.</span><span class="nf">strip_heredoc</span><span class="sh"> This command does such and such. Supported options are: -h This message ... </span><span class="no"> USAGE</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="if options[:usage] puts <<-USAGE.strip_heredoc This command does such and such. Supported options are: -h This message ... USAGE end ">Copy</button> </div> <p>the user would see the usage message aligned against the left margin.</p><p>Technically, it looks for the least indented line in the whole string, and removes that amount of leading whitespace.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/strip.rb">active_support/core_ext/string/strip.rb</a></code>.</p></div><h3 id="indent"><a class="anchorlink" href="#indent" data-turbo="false"><span>5.10</span> <code>indent</code></a></h3><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-indent"><code>indent</code></a> method indents the lines in the receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="o"><<</span><span class="no">EOS</span><span class="p">.</span><span class="nf">indent</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="sh"> def some_method some_code end </span><span class="no">EOS</span> <span class="c1"># =></span> <span class="k">def</span> <span class="nf">some_method</span> <span class="n">some_code</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<<EOS.indent(2) def some_method some_code end EOS # => def some_method some_code end ">Copy</button> </div> <p>The second argument, <code>indent_string</code>, specifies which indent string to use. The default is <code>nil</code>, which tells the method to make an educated guess peeking at the first indented line, and fallback to a space if there is none.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">" foo"</span><span class="p">.</span><span class="nf">indent</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => " foo"</span> <span class="s2">"foo</span><span class="se">\n\t\t</span><span class="s2">bar"</span><span class="p">.</span><span class="nf">indent</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => "\t\tfoo\n\t\t\t\tbar"</span> <span class="s2">"foo"</span><span class="p">.</span><span class="nf">indent</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="p">)</span> <span class="c1"># => "\t\tfoo"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="" foo".indent(2) # => " foo" "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar" "foo".indent(2, "\t") # => "\t\tfoo" ">Copy</button> </div> <p>While <code>indent_string</code> is typically one space or tab, it may be any string.</p><p>The third argument, <code>indent_empty_lines</code>, is a flag that says whether empty lines should be indented. Default is false.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"foo</span><span class="se">\n\n</span><span class="s2">bar"</span><span class="p">.</span><span class="nf">indent</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => " foo\n\n bar"</span> <span class="s2">"foo</span><span class="se">\n\n</span><span class="s2">bar"</span><span class="p">.</span><span class="nf">indent</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="kp">nil</span><span class="p">,</span> <span class="kp">true</span><span class="p">)</span> <span class="c1"># => " foo\n \n bar"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""foo\n\nbar".indent(2) # => " foo\n\n bar" "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar" ">Copy</button> </div> <p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-indent-21"><code>indent!</code></a> method performs indentation in-place.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/indent.rb">active_support/core_ext/string/indent.rb</a></code>.</p></div><h3 id="access"><a class="anchorlink" href="#access" data-turbo="false"><span>5.11</span> Access</a></h3><h4 id="at-position"><a class="anchorlink" href="#at-position" data-turbo="false"><span>5.11.1</span> <code>at(position)</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-at"><code>at</code></a> method returns the character of the string at position <code>position</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"hello"</span><span class="p">.</span><span class="nf">at</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => "h"</span> <span class="s2">"hello"</span><span class="p">.</span><span class="nf">at</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="c1"># => "o"</span> <span class="s2">"hello"</span><span class="p">.</span><span class="nf">at</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => "o"</span> <span class="s2">"hello"</span><span class="p">.</span><span class="nf">at</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># => nil</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""hello".at(0) # => "h" "hello".at(4) # => "o" "hello".at(-1) # => "o" "hello".at(10) # => nil ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/access.rb">active_support/core_ext/string/access.rb</a></code>.</p></div><h4 id="from-position"><a class="anchorlink" href="#from-position" data-turbo="false"><span>5.11.2</span> <code>from(position)</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-from"><code>from</code></a> method returns the substring of the string starting at position <code>position</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"hello"</span><span class="p">.</span><span class="nf">from</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => "hello"</span> <span class="s2">"hello"</span><span class="p">.</span><span class="nf">from</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => "llo"</span> <span class="s2">"hello"</span><span class="p">.</span><span class="nf">from</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => "lo"</span> <span class="s2">"hello"</span><span class="p">.</span><span class="nf">from</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># => nil</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""hello".from(0) # => "hello" "hello".from(2) # => "llo" "hello".from(-2) # => "lo" "hello".from(10) # => nil ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/access.rb">active_support/core_ext/string/access.rb</a></code>.</p></div><h4 id="to-position"><a class="anchorlink" href="#to-position" data-turbo="false"><span>5.11.3</span> <code>to(position)</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-to"><code>to</code></a> method returns the substring of the string up to position <code>position</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"hello"</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => "h"</span> <span class="s2">"hello"</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => "hel"</span> <span class="s2">"hello"</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => "hell"</span> <span class="s2">"hello"</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># => "hello"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""hello".to(0) # => "h" "hello".to(2) # => "hel" "hello".to(-2) # => "hell" "hello".to(10) # => "hello" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/access.rb">active_support/core_ext/string/access.rb</a></code>.</p></div><h4 id="first-limit-1"><a class="anchorlink" href="#first-limit-1" data-turbo="false"><span>5.11.4</span> <code>first(limit = 1)</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-first"><code>first</code></a> method returns a substring containing the first <code>limit</code> characters of the string.</p><p>The call <code>str.first(n)</code> is equivalent to <code>str.to(n-1)</code> if <code>n</code> > 0, and returns an empty string for <code>n</code> == 0.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/access.rb">active_support/core_ext/string/access.rb</a></code>.</p></div><h4 id="last-limit-1"><a class="anchorlink" href="#last-limit-1" data-turbo="false"><span>5.11.5</span> <code>last(limit = 1)</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-last"><code>last</code></a> method returns a substring containing the last <code>limit</code> characters of the string.</p><p>The call <code>str.last(n)</code> is equivalent to <code>str.from(-n)</code> if <code>n</code> > 0, and returns an empty string for <code>n</code> == 0.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/access.rb">active_support/core_ext/string/access.rb</a></code>.</p></div><h3 id="inflections"><a class="anchorlink" href="#inflections" data-turbo="false"><span>5.12</span> Inflections</a></h3><h4 id="pluralize"><a class="anchorlink" href="#pluralize" data-turbo="false"><span>5.12.1</span> <code>pluralize</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-pluralize"><code>pluralize</code></a> returns the plural of its receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"table"</span><span class="p">.</span><span class="nf">pluralize</span> <span class="c1"># => "tables"</span> <span class="s2">"ruby"</span><span class="p">.</span><span class="nf">pluralize</span> <span class="c1"># => "rubies"</span> <span class="s2">"equipment"</span><span class="p">.</span><span class="nf">pluralize</span> <span class="c1"># => "equipment"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""table".pluralize # => "tables" "ruby".pluralize # => "rubies" "equipment".pluralize # => "equipment" ">Copy</button> </div> <p>As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in <code>config/initializers/inflections.rb</code>. This file is generated by default, by the <code>rails new</code> command and has instructions in comments.</p><p><code>pluralize</code> can also take an optional <code>count</code> parameter. If <code>count == 1</code> the singular form will be returned. For any other value of <code>count</code> the plural form will be returned:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"dude"</span><span class="p">.</span><span class="nf">pluralize</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => "dudes"</span> <span class="s2">"dude"</span><span class="p">.</span><span class="nf">pluralize</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => "dude"</span> <span class="s2">"dude"</span><span class="p">.</span><span class="nf">pluralize</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => "dudes"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""dude".pluralize(0) # => "dudes" "dude".pluralize(1) # => "dude" "dude".pluralize(2) # => "dudes" ">Copy</button> </div> <p>Active Record uses this method to compute the default table name that corresponds to a model:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># active_record/model_schema.rb</span> <span class="k">def</span> <span class="nf">undecorated_table_name</span><span class="p">(</span><span class="n">model_name</span><span class="p">)</span> <span class="n">table_name</span> <span class="o">=</span> <span class="n">model_name</span><span class="p">.</span><span class="nf">to_s</span><span class="p">.</span><span class="nf">demodulize</span><span class="p">.</span><span class="nf">underscore</span> <span class="n">pluralize_table_names</span> <span class="p">?</span> <span class="n">table_name</span><span class="p">.</span><span class="nf">pluralize</span> <span class="p">:</span> <span class="n">table_name</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# active_record/model_schema.rb def undecorated_table_name(model_name) table_name = model_name.to_s.demodulize.underscore pluralize_table_names ? table_name.pluralize : table_name end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="singularize"><a class="anchorlink" href="#singularize" data-turbo="false"><span>5.12.2</span> <code>singularize</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-singularize"><code>singularize</code></a> method is the inverse of <code>pluralize</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"tables"</span><span class="p">.</span><span class="nf">singularize</span> <span class="c1"># => "table"</span> <span class="s2">"rubies"</span><span class="p">.</span><span class="nf">singularize</span> <span class="c1"># => "ruby"</span> <span class="s2">"equipment"</span><span class="p">.</span><span class="nf">singularize</span> <span class="c1"># => "equipment"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""tables".singularize # => "table" "rubies".singularize # => "ruby" "equipment".singularize # => "equipment" ">Copy</button> </div> <p>Associations compute the name of the corresponding default associated class using this method:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># active_record/reflection.rb</span> <span class="k">def</span> <span class="nf">derive_class_name</span> <span class="n">class_name</span> <span class="o">=</span> <span class="nb">name</span><span class="p">.</span><span class="nf">to_s</span><span class="p">.</span><span class="nf">camelize</span> <span class="n">class_name</span> <span class="o">=</span> <span class="n">class_name</span><span class="p">.</span><span class="nf">singularize</span> <span class="k">if</span> <span class="n">collection?</span> <span class="n">class_name</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# active_record/reflection.rb def derive_class_name class_name = name.to_s.camelize class_name = class_name.singularize if collection? class_name end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="camelize"><a class="anchorlink" href="#camelize" data-turbo="false"><span>5.12.3</span> <code>camelize</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-camelize"><code>camelize</code></a> returns its receiver in camel case:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"product"</span><span class="p">.</span><span class="nf">camelize</span> <span class="c1"># => "Product"</span> <span class="s2">"admin_user"</span><span class="p">.</span><span class="nf">camelize</span> <span class="c1"># => "AdminUser"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""product".camelize # => "Product" "admin_user".camelize # => "AdminUser" ">Copy</button> </div> <p>As a rule of thumb you can think of this method as the one that transforms paths into Ruby class or module names, where slashes separate namespaces:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"backoffice/session"</span><span class="p">.</span><span class="nf">camelize</span> <span class="c1"># => "Backoffice::Session"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""backoffice/session".camelize # => "Backoffice::Session" ">Copy</button> </div> <p>For example, Action Pack uses this method to load the class that provides a certain session store:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># action_controller/metal/session_management.rb</span> <span class="k">def</span> <span class="nf">session_store</span><span class="o">=</span><span class="p">(</span><span class="n">store</span><span class="p">)</span> <span class="vc">@@session_store</span> <span class="o">=</span> <span class="n">store</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="no">Symbol</span><span class="p">)</span> <span class="p">?</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">Session</span><span class="p">.</span><span class="nf">const_get</span><span class="p">(</span><span class="n">store</span><span class="p">.</span><span class="nf">to_s</span><span class="p">.</span><span class="nf">camelize</span><span class="p">)</span> <span class="p">:</span> <span class="n">store</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# action_controller/metal/session_management.rb def session_store=(store) @@session_store = store.is_a?(Symbol) ? ActionDispatch::Session.const_get(store.to_s.camelize) : store end ">Copy</button> </div> <p><code>camelize</code> accepts an optional argument, it can be <code>:upper</code> (default), or <code>:lower</code>. With the latter the first letter becomes lowercase:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"visual_effect"</span><span class="p">.</span><span class="nf">camelize</span><span class="p">(</span><span class="ss">:lower</span><span class="p">)</span> <span class="c1"># => "visualEffect"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""visual_effect".camelize(:lower) # => "visualEffect" ">Copy</button> </div> <p>That may be handy to compute method names in a language that follows that convention, for example JavaScript.</p><div class="interstitial info"><p>As a rule of thumb you can think of <code>camelize</code> as the inverse of <code>underscore</code>, though there are cases where that does not hold: <code>"SSLError".underscore.camelize</code> gives back <code>"SslError"</code>. To support cases such as this, Active Support allows you to specify acronyms in <code>config/initializers/inflections.rb</code>:</p></div><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Inflector</span><span class="p">.</span><span class="nf">inflections</span> <span class="k">do</span> <span class="o">|</span><span class="n">inflect</span><span class="o">|</span> <span class="n">inflect</span><span class="p">.</span><span class="nf">acronym</span> <span class="s2">"SSL"</span> <span class="k">end</span> <span class="s2">"SSLError"</span><span class="p">.</span><span class="nf">underscore</span><span class="p">.</span><span class="nf">camelize</span> <span class="c1"># => "SSLError"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="ActiveSupport::Inflector.inflections do |inflect| inflect.acronym "SSL" end "SSLError".underscore.camelize # => "SSLError" ">Copy</button> </div> <p><code>camelize</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-camelcase"><code>camelcase</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="underscore"><a class="anchorlink" href="#underscore" data-turbo="false"><span>5.12.4</span> <code>underscore</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-underscore"><code>underscore</code></a> goes the other way around, from camel case to paths:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Product"</span><span class="p">.</span><span class="nf">underscore</span> <span class="c1"># => "product"</span> <span class="s2">"AdminUser"</span><span class="p">.</span><span class="nf">underscore</span> <span class="c1"># => "admin_user"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Product".underscore # => "product" "AdminUser".underscore # => "admin_user" ">Copy</button> </div> <p>Also converts "::" back to "/":</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Backoffice::Session"</span><span class="p">.</span><span class="nf">underscore</span> <span class="c1"># => "backoffice/session"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Backoffice::Session".underscore # => "backoffice/session" ">Copy</button> </div> <p>and understands strings that start with lowercase:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"visualEffect"</span><span class="p">.</span><span class="nf">underscore</span> <span class="c1"># => "visual_effect"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""visualEffect".underscore # => "visual_effect" ">Copy</button> </div> <p><code>underscore</code> accepts no argument though.</p><p>Rails uses <code>underscore</code> to get a lowercased name for controller classes:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># actionpack/lib/abstract_controller/base.rb</span> <span class="k">def</span> <span class="nf">controller_path</span> <span class="vi">@controller_path</span> <span class="o">||=</span> <span class="nb">name</span><span class="p">.</span><span class="nf">delete_suffix</span><span class="p">(</span><span class="s2">"Controller"</span><span class="p">).</span><span class="nf">underscore</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# actionpack/lib/abstract_controller/base.rb def controller_path @controller_path ||= name.delete_suffix("Controller").underscore end ">Copy</button> </div> <p>For example, that value is the one you get in <code>params[:controller]</code>.</p><div class="interstitial info"><p>As a rule of thumb you can think of <code>underscore</code> as the inverse of <code>camelize</code>, though there are cases where that does not hold. For example, <code>"SSLError".underscore.camelize</code> gives back <code>"SslError"</code>.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="titleize"><a class="anchorlink" href="#titleize" data-turbo="false"><span>5.12.5</span> <code>titleize</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-titleize"><code>titleize</code></a> capitalizes the words in the receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"alice in wonderland"</span><span class="p">.</span><span class="nf">titleize</span> <span class="c1"># => "Alice In Wonderland"</span> <span class="s2">"fermat's enigma"</span><span class="p">.</span><span class="nf">titleize</span> <span class="c1"># => "Fermat's Enigma"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""alice in wonderland".titleize # => "Alice In Wonderland" "fermat's enigma".titleize # => "Fermat's Enigma" ">Copy</button> </div> <p><code>titleize</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-titlecase"><code>titlecase</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="dasherize"><a class="anchorlink" href="#dasherize" data-turbo="false"><span>5.12.6</span> <code>dasherize</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-dasherize"><code>dasherize</code></a> replaces the underscores in the receiver with dashes:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"name"</span><span class="p">.</span><span class="nf">dasherize</span> <span class="c1"># => "name"</span> <span class="s2">"contact_data"</span><span class="p">.</span><span class="nf">dasherize</span> <span class="c1"># => "contact-data"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""name".dasherize # => "name" "contact_data".dasherize # => "contact-data" ">Copy</button> </div> <p>The XML serializer of models uses this method to dasherize node names:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># active_model/serializers/xml.rb</span> <span class="k">def</span> <span class="nf">reformat_name</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span> <span class="nb">name</span> <span class="o">=</span> <span class="nb">name</span><span class="p">.</span><span class="nf">camelize</span> <span class="k">if</span> <span class="n">camelize?</span> <span class="n">dasherize?</span> <span class="p">?</span> <span class="nb">name</span><span class="p">.</span><span class="nf">dasherize</span> <span class="p">:</span> <span class="nb">name</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# active_model/serializers/xml.rb def reformat_name(name) name = name.camelize if camelize? dasherize? ? name.dasherize : name end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="demodulize"><a class="anchorlink" href="#demodulize" data-turbo="false"><span>5.12.7</span> <code>demodulize</code></a></h4><p>Given a string with a qualified constant name, <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-demodulize"><code>demodulize</code></a> returns the very constant name, that is, the rightmost part of it:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Product"</span><span class="p">.</span><span class="nf">demodulize</span> <span class="c1"># => "Product"</span> <span class="s2">"Backoffice::UsersController"</span><span class="p">.</span><span class="nf">demodulize</span> <span class="c1"># => "UsersController"</span> <span class="s2">"Admin::Hotel::ReservationUtils"</span><span class="p">.</span><span class="nf">demodulize</span> <span class="c1"># => "ReservationUtils"</span> <span class="s2">"::Inflections"</span><span class="p">.</span><span class="nf">demodulize</span> <span class="c1"># => "Inflections"</span> <span class="s2">""</span><span class="p">.</span><span class="nf">demodulize</span> <span class="c1"># => ""</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Product".demodulize # => "Product" "Backoffice::UsersController".demodulize # => "UsersController" "Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils" "::Inflections".demodulize # => "Inflections" "".demodulize # => "" ">Copy</button> </div> <p>Active Record for example uses this method to compute the name of a counter cache column:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># active_record/reflection.rb</span> <span class="k">def</span> <span class="nf">counter_cache_column</span> <span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:counter_cache</span><span class="p">]</span> <span class="o">==</span> <span class="kp">true</span> <span class="s2">"</span><span class="si">#{</span><span class="n">active_record</span><span class="p">.</span><span class="nf">name</span><span class="p">.</span><span class="nf">demodulize</span><span class="p">.</span><span class="nf">underscore</span><span class="p">.</span><span class="nf">pluralize</span><span class="si">}</span><span class="s2">_count"</span> <span class="k">elsif</span> <span class="n">options</span><span class="p">[</span><span class="ss">:counter_cache</span><span class="p">]</span> <span class="n">options</span><span class="p">[</span><span class="ss">:counter_cache</span><span class="p">]</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# active_record/reflection.rb def counter_cache_column if options[:counter_cache] == true "#{active_record.name.demodulize.underscore.pluralize}_count" elsif options[:counter_cache] options[:counter_cache] end end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="deconstantize"><a class="anchorlink" href="#deconstantize" data-turbo="false"><span>5.12.8</span> <code>deconstantize</code></a></h4><p>Given a string with a qualified constant reference expression, <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-deconstantize"><code>deconstantize</code></a> removes the rightmost segment, generally leaving the name of the constant's container:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Product"</span><span class="p">.</span><span class="nf">deconstantize</span> <span class="c1"># => ""</span> <span class="s2">"Backoffice::UsersController"</span><span class="p">.</span><span class="nf">deconstantize</span> <span class="c1"># => "Backoffice"</span> <span class="s2">"Admin::Hotel::ReservationUtils"</span><span class="p">.</span><span class="nf">deconstantize</span> <span class="c1"># => "Admin::Hotel"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Product".deconstantize # => "" "Backoffice::UsersController".deconstantize # => "Backoffice" "Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="parameterize"><a class="anchorlink" href="#parameterize" data-turbo="false"><span>5.12.9</span> <code>parameterize</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-parameterize"><code>parameterize</code></a> normalizes its receiver in a way that can be used in pretty URLs.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"John Smith"</span><span class="p">.</span><span class="nf">parameterize</span> <span class="c1"># => "john-smith"</span> <span class="s2">"Kurt Gödel"</span><span class="p">.</span><span class="nf">parameterize</span> <span class="c1"># => "kurt-godel"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""John Smith".parameterize # => "john-smith" "Kurt Gödel".parameterize # => "kurt-godel" ">Copy</button> </div> <p>To preserve the case of the string, set the <code>preserve_case</code> argument to true. By default, <code>preserve_case</code> is set to false.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"John Smith"</span><span class="p">.</span><span class="nf">parameterize</span><span class="p">(</span><span class="ss">preserve_case: </span><span class="kp">true</span><span class="p">)</span> <span class="c1"># => "John-Smith"</span> <span class="s2">"Kurt Gödel"</span><span class="p">.</span><span class="nf">parameterize</span><span class="p">(</span><span class="ss">preserve_case: </span><span class="kp">true</span><span class="p">)</span> <span class="c1"># => "Kurt-Godel"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""John Smith".parameterize(preserve_case: true) # => "John-Smith" "Kurt Gödel".parameterize(preserve_case: true) # => "Kurt-Godel" ">Copy</button> </div> <p>To use a custom separator, override the <code>separator</code> argument.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"John Smith"</span><span class="p">.</span><span class="nf">parameterize</span><span class="p">(</span><span class="ss">separator: </span><span class="s2">"_"</span><span class="p">)</span> <span class="c1"># => "john_smith"</span> <span class="s2">"Kurt Gödel"</span><span class="p">.</span><span class="nf">parameterize</span><span class="p">(</span><span class="ss">separator: </span><span class="s2">"_"</span><span class="p">)</span> <span class="c1"># => "kurt_godel"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""John Smith".parameterize(separator: "_") # => "john_smith" "Kurt Gödel".parameterize(separator: "_") # => "kurt_godel" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="tableize"><a class="anchorlink" href="#tableize" data-turbo="false"><span>5.12.10</span> <code>tableize</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-tableize"><code>tableize</code></a> is <code>underscore</code> followed by <code>pluralize</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Person"</span><span class="p">.</span><span class="nf">tableize</span> <span class="c1"># => "people"</span> <span class="s2">"Invoice"</span><span class="p">.</span><span class="nf">tableize</span> <span class="c1"># => "invoices"</span> <span class="s2">"InvoiceLine"</span><span class="p">.</span><span class="nf">tableize</span> <span class="c1"># => "invoice_lines"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Person".tableize # => "people" "Invoice".tableize # => "invoices" "InvoiceLine".tableize # => "invoice_lines" ">Copy</button> </div> <p>As a rule of thumb, <code>tableize</code> returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight <code>tableize</code> indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="classify"><a class="anchorlink" href="#classify" data-turbo="false"><span>5.12.11</span> <code>classify</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-classify"><code>classify</code></a> is the inverse of <code>tableize</code>. It gives you the class name corresponding to a table name:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"people"</span><span class="p">.</span><span class="nf">classify</span> <span class="c1"># => "Person"</span> <span class="s2">"invoices"</span><span class="p">.</span><span class="nf">classify</span> <span class="c1"># => "Invoice"</span> <span class="s2">"invoice_lines"</span><span class="p">.</span><span class="nf">classify</span> <span class="c1"># => "InvoiceLine"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""people".classify # => "Person" "invoices".classify # => "Invoice" "invoice_lines".classify # => "InvoiceLine" ">Copy</button> </div> <p>The method understands qualified table names:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"highrise_production.companies"</span><span class="p">.</span><span class="nf">classify</span> <span class="c1"># => "Company"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""highrise_production.companies".classify # => "Company" ">Copy</button> </div> <p>Note that <code>classify</code> returns a class name as a string. You can get the actual class object by invoking <code>constantize</code> on it, explained next.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="constantize"><a class="anchorlink" href="#constantize" data-turbo="false"><span>5.12.12</span> <code>constantize</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-constantize"><code>constantize</code></a> resolves the constant reference expression in its receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"Integer"</span><span class="p">.</span><span class="nf">constantize</span> <span class="c1"># => Integer</span> <span class="k">module</span> <span class="nn">M</span> <span class="no">X</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">end</span> <span class="s2">"M::X"</span><span class="p">.</span><span class="nf">constantize</span> <span class="c1"># => 1</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""Integer".constantize # => Integer module M X = 1 end "M::X".constantize # => 1 ">Copy</button> </div> <p>If the string evaluates to no known constant, or its content is not even a valid constant name, <code>constantize</code> raises <code>NameError</code>.</p><p>Constant name resolution by <code>constantize</code> starts always at the top-level <code>Object</code> even if there is no leading "::".</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">X</span> <span class="o">=</span> <span class="ss">:in_Object</span> <span class="k">module</span> <span class="nn">M</span> <span class="no">X</span> <span class="o">=</span> <span class="ss">:in_M</span> <span class="no">X</span> <span class="c1"># => :in_M</span> <span class="s2">"::X"</span><span class="p">.</span><span class="nf">constantize</span> <span class="c1"># => :in_Object</span> <span class="s2">"X"</span><span class="p">.</span><span class="nf">constantize</span> <span class="c1"># => :in_Object (!)</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="X = :in_Object module M X = :in_M X # => :in_M "::X".constantize # => :in_Object "X".constantize # => :in_Object (!) end ">Copy</button> </div> <p>So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated.</p><p>Mailer test cases obtain the mailer being tested from the name of the test class using <code>constantize</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># action_mailer/test_case.rb</span> <span class="k">def</span> <span class="nf">determine_default_mailer</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span> <span class="nb">name</span><span class="p">.</span><span class="nf">delete_suffix</span><span class="p">(</span><span class="s2">"Test"</span><span class="p">).</span><span class="nf">constantize</span> <span class="k">rescue</span> <span class="no">NameError</span> <span class="o">=></span> <span class="n">e</span> <span class="k">raise</span> <span class="no">NonInferrableMailerError</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# action_mailer/test_case.rb def determine_default_mailer(name) name.delete_suffix("Test").constantize rescue NameError => e raise NonInferrableMailerError.new(name) end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="humanize"><a class="anchorlink" href="#humanize" data-turbo="false"><span>5.12.13</span> <code>humanize</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-humanize"><code>humanize</code></a> tweaks an attribute name for display to end users.</p><p>Specifically, it performs these transformations:</p> <ul> <li>Applies human inflection rules to the argument.</li> <li>Deletes leading underscores, if any.</li> <li>Removes a "_id" suffix if present.</li> <li>Replaces underscores with spaces, if any.</li> <li>Downcases all words except acronyms.</li> <li>Capitalizes the first word.</li> </ul> <p>The capitalization of the first word can be turned off by setting the <code>:capitalize</code> option to false (default is true).</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"name"</span><span class="p">.</span><span class="nf">humanize</span> <span class="c1"># => "Name"</span> <span class="s2">"author_id"</span><span class="p">.</span><span class="nf">humanize</span> <span class="c1"># => "Author"</span> <span class="s2">"author_id"</span><span class="p">.</span><span class="nf">humanize</span><span class="p">(</span><span class="ss">capitalize: </span><span class="kp">false</span><span class="p">)</span> <span class="c1"># => "author"</span> <span class="s2">"comments_count"</span><span class="p">.</span><span class="nf">humanize</span> <span class="c1"># => "Comments count"</span> <span class="s2">"_id"</span><span class="p">.</span><span class="nf">humanize</span> <span class="c1"># => "Id"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""name".humanize # => "Name" "author_id".humanize # => "Author" "author_id".humanize(capitalize: false) # => "author" "comments_count".humanize # => "Comments count" "_id".humanize # => "Id" ">Copy</button> </div> <p>If "SSL" was defined to be an acronym:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"ssl_error"</span><span class="p">.</span><span class="nf">humanize</span> <span class="c1"># => "SSL error"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""ssl_error".humanize # => "SSL error" ">Copy</button> </div> <p>The helper method <code>full_messages</code> uses <code>humanize</code> as a fallback to include attribute names:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">full_messages</span> <span class="n">map</span> <span class="p">{</span> <span class="o">|</span><span class="n">attribute</span><span class="p">,</span> <span class="n">message</span><span class="o">|</span> <span class="n">full_message</span><span class="p">(</span><span class="n">attribute</span><span class="p">,</span> <span class="n">message</span><span class="p">)</span> <span class="p">}</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">full_message</span> <span class="c1"># ...</span> <span class="n">attr_name</span> <span class="o">=</span> <span class="n">attribute</span><span class="p">.</span><span class="nf">to_s</span><span class="p">.</span><span class="nf">tr</span><span class="p">(</span><span class="s2">"."</span><span class="p">,</span> <span class="s2">"_"</span><span class="p">).</span><span class="nf">humanize</span> <span class="n">attr_name</span> <span class="o">=</span> <span class="vi">@base</span><span class="p">.</span><span class="nf">class</span><span class="p">.</span><span class="nf">human_attribute_name</span><span class="p">(</span><span class="n">attribute</span><span class="p">,</span> <span class="ss">default: </span><span class="n">attr_name</span><span class="p">)</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def full_messages map { |attribute, message| full_message(attribute, message) } end def full_message # ... attr_name = attribute.to_s.tr(".", "_").humanize attr_name = @base.class.human_attribute_name(attribute, default: attr_name) # ... end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="foreign-key"><a class="anchorlink" href="#foreign-key" data-turbo="false"><span>5.12.14</span> <code>foreign_key</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-foreign_key"><code>foreign_key</code></a> gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds "_id":</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"User"</span><span class="p">.</span><span class="nf">foreign_key</span> <span class="c1"># => "user_id"</span> <span class="s2">"InvoiceLine"</span><span class="p">.</span><span class="nf">foreign_key</span> <span class="c1"># => "invoice_line_id"</span> <span class="s2">"Admin::Session"</span><span class="p">.</span><span class="nf">foreign_key</span> <span class="c1"># => "session_id"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""User".foreign_key # => "user_id" "InvoiceLine".foreign_key # => "invoice_line_id" "Admin::Session".foreign_key # => "session_id" ">Copy</button> </div> <p>Pass a false argument if you do not want the underscore in "_id":</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"User"</span><span class="p">.</span><span class="nf">foreign_key</span><span class="p">(</span><span class="kp">false</span><span class="p">)</span> <span class="c1"># => "userid"</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""User".foreign_key(false) # => "userid" ">Copy</button> </div> <p>Associations use this method to infer foreign keys, for example <code>has_one</code> and <code>has_many</code> do this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># active_record/associations.rb</span> <span class="n">foreign_key</span> <span class="o">=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:foreign_key</span><span class="p">]</span> <span class="o">||</span> <span class="n">reflection</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">name</span><span class="p">.</span><span class="nf">foreign_key</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# active_record/associations.rb foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="upcase-first"><a class="anchorlink" href="#upcase-first" data-turbo="false"><span>5.12.15</span> <code>upcase_first</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-upcase_first"><code>upcase_first</code></a> capitalizes the first letter of the receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"employee salary"</span><span class="p">.</span><span class="nf">upcase_first</span> <span class="c1"># => "Employee salary"</span> <span class="s2">""</span><span class="p">.</span><span class="nf">upcase_first</span> <span class="c1"># => ""</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""employee salary".upcase_first # => "Employee salary" "".upcase_first # => "" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h4 id="downcase-first"><a class="anchorlink" href="#downcase-first" data-turbo="false"><span>5.12.16</span> <code>downcase_first</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-downcase_first"><code>downcase_first</code></a> converts the first letter of the receiver to lowercase:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"If I had read Alice in Wonderland"</span><span class="p">.</span><span class="nf">downcase_first</span> <span class="c1"># => "if I had read Alice in Wonderland"</span> <span class="s2">""</span><span class="p">.</span><span class="nf">downcase_first</span> <span class="c1"># => ""</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""If I had read Alice in Wonderland".downcase_first # => "if I had read Alice in Wonderland" "".downcase_first # => "" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/inflections.rb">active_support/core_ext/string/inflections.rb</a></code>.</p></div><h3 id="extensions-to-string-conversions"><a class="anchorlink" href="#extensions-to-string-conversions" data-turbo="false"><span>5.13</span> Conversions</a></h3><h4 id="to-date-to-time-to-datetime"><a class="anchorlink" href="#to-date-to-time-to-datetime" data-turbo="false"><span>5.13.1</span> <code>to_date</code>, <code>to_time</code>, <code>to_datetime</code></a></h4><p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-to_date"><code>to_date</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-to_time"><code>to_time</code></a>, and <a href="https://api.rubyonrails.org/v8.0.0/classes/String.html#method-i-to_datetime"><code>to_datetime</code></a> are basically convenience wrappers around <code>Date._parse</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"2010-07-27"</span><span class="p">.</span><span class="nf">to_date</span> <span class="c1"># => Tue, 27 Jul 2010</span> <span class="s2">"2010-07-27 23:37:00"</span><span class="p">.</span><span class="nf">to_time</span> <span class="c1"># => 2010-07-27 23:37:00 +0200</span> <span class="s2">"2010-07-27 23:37:00"</span><span class="p">.</span><span class="nf">to_datetime</span> <span class="c1"># => Tue, 27 Jul 2010 23:37:00 +0000</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""2010-07-27".to_date # => Tue, 27 Jul 2010 "2010-07-27 23:37:00".to_time # => 2010-07-27 23:37:00 +0200 "2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000 ">Copy</button> </div> <p><code>to_time</code> receives an optional argument <code>:utc</code> or <code>:local</code>, to indicate which time zone you want the time in:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="s2">"2010-07-27 23:42:00"</span><span class="p">.</span><span class="nf">to_time</span><span class="p">(</span><span class="ss">:utc</span><span class="p">)</span> <span class="c1"># => 2010-07-27 23:42:00 UTC</span> <span class="s2">"2010-07-27 23:42:00"</span><span class="p">.</span><span class="nf">to_time</span><span class="p">(</span><span class="ss">:local</span><span class="p">)</span> <span class="c1"># => 2010-07-27 23:42:00 +0200</span> </code></pre> <button class="clipboard-button" data-clipboard-text=""2010-07-27 23:42:00".to_time(:utc) # => 2010-07-27 23:42:00 UTC "2010-07-27 23:42:00".to_time(:local) # => 2010-07-27 23:42:00 +0200 ">Copy</button> </div> <p>Default is <code>:local</code>.</p><p>Please refer to the documentation of <code>Date._parse</code> for further details.</p><div class="interstitial info"><p>The three of them return <code>nil</code> for blank receivers.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/string/conversions.rb">active_support/core_ext/string/conversions.rb</a></code>.</p></div><h2 id="extensions-to-symbol"><a class="anchorlink" href="#extensions-to-symbol" data-turbo="false"><span>6</span> Extensions to <code>Symbol</code></a></h2><h3 id="extensions-to-symbol-starts-with-questionmark-and-ends-with-questionmark"><a class="anchorlink" href="#extensions-to-symbol-starts-with-questionmark-and-ends-with-questionmark" data-turbo="false"><span>6.1</span> <code>starts_with?</code> and <code>ends_with?</code></a></h3><p>Active Support defines 3rd person aliases of <code>Symbol#start_with?</code> and <code>Symbol#end_with?</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="ss">:foo</span><span class="p">.</span><span class="nf">starts_with?</span><span class="p">(</span><span class="s2">"f"</span><span class="p">)</span> <span class="c1"># => true</span> <span class="ss">:foo</span><span class="p">.</span><span class="nf">ends_with?</span><span class="p">(</span><span class="s2">"o"</span><span class="p">)</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text=":foo.starts_with?("f") # => true :foo.ends_with?("o") # => true ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/symbol/starts_ends_with.rb">active_support/core_ext/symbol/starts_ends_with.rb</a></code>.</p></div><h2 id="extensions-to-numeric"><a class="anchorlink" href="#extensions-to-numeric" data-turbo="false"><span>7</span> Extensions to <code>Numeric</code></a></h2><h3 id="bytes"><a class="anchorlink" href="#bytes" data-turbo="false"><span>7.1</span> Bytes</a></h3><p>All numbers respond to these methods:</p> <ul> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-bytes"><code>bytes</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-kilobytes"><code>kilobytes</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-megabytes"><code>megabytes</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-gigabytes"><code>gigabytes</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-terabytes"><code>terabytes</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-petabytes"><code>petabytes</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-exabytes"><code>exabytes</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-zettabytes"><code>zettabytes</code></a></li> </ul> <p>They return the corresponding amount of bytes, using a conversion factor of 1024:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">2</span><span class="p">.</span><span class="nf">kilobytes</span> <span class="c1"># => 2048</span> <span class="mi">3</span><span class="p">.</span><span class="nf">megabytes</span> <span class="c1"># => 3145728</span> <span class="mf">3.5</span><span class="p">.</span><span class="nf">gigabytes</span> <span class="c1"># => 3758096384.0</span> <span class="o">-</span><span class="mi">4</span><span class="p">.</span><span class="nf">exabytes</span> <span class="c1"># => -4611686018427387904</span> </code></pre> <button class="clipboard-button" data-clipboard-text="2.kilobytes # => 2048 3.megabytes # => 3145728 3.5.gigabytes # => 3758096384.0 -4.exabytes # => -4611686018427387904 ">Copy</button> </div> <p>Singular forms are aliased so you are able to say:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">1</span><span class="p">.</span><span class="nf">megabyte</span> <span class="c1"># => 1048576</span> </code></pre> <button class="clipboard-button" data-clipboard-text="1.megabyte # => 1048576 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/numeric/bytes.rb">active_support/core_ext/numeric/bytes.rb</a></code>.</p></div><h3 id="extensions-to-numeric-time"><a class="anchorlink" href="#extensions-to-numeric-time" data-turbo="false"><span>7.2</span> Time</a></h3><p>The following methods:</p> <ul> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-seconds"><code>seconds</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-minutes"><code>minutes</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-hours"><code>hours</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-days"><code>days</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-weeks"><code>weeks</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Numeric.html#method-i-fortnights"><code>fortnights</code></a></li> </ul> <p>enable time declarations and calculations, like <code>45.minutes + 2.hours + 4.weeks</code>. Their return values can also be added to or subtracted from Time objects.</p><p>These methods can be combined with <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Duration.html#method-i-from_now"><code>from_now</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Duration.html#method-i-ago"><code>ago</code></a>, etc, for precise date calculations. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># equivalent to Time.current.advance(days: 1)</span> <span class="mi">1</span><span class="p">.</span><span class="nf">day</span><span class="p">.</span><span class="nf">from_now</span> <span class="c1"># equivalent to Time.current.advance(weeks: 2)</span> <span class="mi">2</span><span class="p">.</span><span class="nf">weeks</span><span class="p">.</span><span class="nf">from_now</span> <span class="c1"># equivalent to Time.current.advance(days: 4, weeks: 5)</span> <span class="p">(</span><span class="mi">4</span><span class="p">.</span><span class="nf">days</span> <span class="o">+</span> <span class="mi">5</span><span class="p">.</span><span class="nf">weeks</span><span class="p">).</span><span class="nf">from_now</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# equivalent to Time.current.advance(days: 1) 1.day.from_now # equivalent to Time.current.advance(weeks: 2) 2.weeks.from_now # equivalent to Time.current.advance(days: 4, weeks: 5) (4.days + 5.weeks).from_now ">Copy</button> </div> <div class="interstitial warning"><p>For other durations please refer to the time extensions to <code>Integer</code>.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/numeric/time.rb">active_support/core_ext/numeric/time.rb</a></code>.</p></div><h3 id="formatting"><a class="anchorlink" href="#formatting" data-turbo="false"><span>7.3</span> Formatting</a></h3><p>Enables the formatting of numbers in a variety of ways.</p><p>Produce a string representation of a number as a telephone number:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">5551234</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:phone</span><span class="p">)</span> <span class="c1"># => 555-1234</span> <span class="mi">1235551234</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:phone</span><span class="p">)</span> <span class="c1"># => 123-555-1234</span> <span class="mi">1235551234</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:phone</span><span class="p">,</span> <span class="ss">area_code: </span><span class="kp">true</span><span class="p">)</span> <span class="c1"># => (123) 555-1234</span> <span class="mi">1235551234</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:phone</span><span class="p">,</span> <span class="ss">delimiter: </span><span class="s2">" "</span><span class="p">)</span> <span class="c1"># => 123 555 1234</span> <span class="mi">1235551234</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:phone</span><span class="p">,</span> <span class="ss">area_code: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">extension: </span><span class="mi">555</span><span class="p">)</span> <span class="c1"># => (123) 555-1234 x 555</span> <span class="mi">1235551234</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:phone</span><span class="p">,</span> <span class="ss">country_code: </span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => +1-123-555-1234</span> </code></pre> <button class="clipboard-button" data-clipboard-text="5551234.to_fs(:phone) # => 555-1234 1235551234.to_fs(:phone) # => 123-555-1234 1235551234.to_fs(:phone, area_code: true) # => (123) 555-1234 1235551234.to_fs(:phone, delimiter: " ") # => 123 555 1234 1235551234.to_fs(:phone, area_code: true, extension: 555) # => (123) 555-1234 x 555 1235551234.to_fs(:phone, country_code: 1) # => +1-123-555-1234 ">Copy</button> </div> <p>Produce a string representation of a number as currency:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mf">1234567890.50</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:currency</span><span class="p">)</span> <span class="c1"># => $1,234,567,890.50</span> <span class="mf">1234567890.506</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:currency</span><span class="p">)</span> <span class="c1"># => $1,234,567,890.51</span> <span class="mf">1234567890.506</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:currency</span><span class="p">,</span> <span class="ss">precision: </span><span class="mi">3</span><span class="p">)</span> <span class="c1"># => $1,234,567,890.506</span> </code></pre> <button class="clipboard-button" data-clipboard-text="1234567890.50.to_fs(:currency) # => $1,234,567,890.50 1234567890.506.to_fs(:currency) # => $1,234,567,890.51 1234567890.506.to_fs(:currency, precision: 3) # => $1,234,567,890.506 ">Copy</button> </div> <p>Produce a string representation of a number as a percentage:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">100</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:percentage</span><span class="p">)</span> <span class="c1"># => 100.000%</span> <span class="mi">100</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:percentage</span><span class="p">,</span> <span class="ss">precision: </span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => 100%</span> <span class="mi">1000</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:percentage</span><span class="p">,</span> <span class="ss">delimiter: </span><span class="s2">"."</span><span class="p">,</span> <span class="ss">separator: </span><span class="s2">","</span><span class="p">)</span> <span class="c1"># => 1.000,000%</span> <span class="mf">302.24398923423</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:percentage</span><span class="p">,</span> <span class="ss">precision: </span><span class="mi">5</span><span class="p">)</span> <span class="c1"># => 302.24399%</span> </code></pre> <button class="clipboard-button" data-clipboard-text="100.to_fs(:percentage) # => 100.000% 100.to_fs(:percentage, precision: 0) # => 100% 1000.to_fs(:percentage, delimiter: ".", separator: ",") # => 1.000,000% 302.24398923423.to_fs(:percentage, precision: 5) # => 302.24399% ">Copy</button> </div> <p>Produce a string representation of a number in delimited form:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">12345678</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:delimited</span><span class="p">)</span> <span class="c1"># => 12,345,678</span> <span class="mf">12345678.05</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:delimited</span><span class="p">)</span> <span class="c1"># => 12,345,678.05</span> <span class="mi">12345678</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:delimited</span><span class="p">,</span> <span class="ss">delimiter: </span><span class="s2">"."</span><span class="p">)</span> <span class="c1"># => 12.345.678</span> <span class="mi">12345678</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:delimited</span><span class="p">,</span> <span class="ss">delimiter: </span><span class="s2">","</span><span class="p">)</span> <span class="c1"># => 12,345,678</span> <span class="mf">12345678.05</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:delimited</span><span class="p">,</span> <span class="ss">separator: </span><span class="s2">" "</span><span class="p">)</span> <span class="c1"># => 12,345,678 05</span> </code></pre> <button class="clipboard-button" data-clipboard-text="12345678.to_fs(:delimited) # => 12,345,678 12345678.05.to_fs(:delimited) # => 12,345,678.05 12345678.to_fs(:delimited, delimiter: ".") # => 12.345.678 12345678.to_fs(:delimited, delimiter: ",") # => 12,345,678 12345678.05.to_fs(:delimited, separator: " ") # => 12,345,678 05 ">Copy</button> </div> <p>Produce a string representation of a number rounded to a precision:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mf">111.2345</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:rounded</span><span class="p">)</span> <span class="c1"># => 111.235</span> <span class="mf">111.2345</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:rounded</span><span class="p">,</span> <span class="ss">precision: </span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => 111.23</span> <span class="mi">13</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:rounded</span><span class="p">,</span> <span class="ss">precision: </span><span class="mi">5</span><span class="p">)</span> <span class="c1"># => 13.00000</span> <span class="mf">389.32314</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:rounded</span><span class="p">,</span> <span class="ss">precision: </span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => 389</span> <span class="mf">111.2345</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:rounded</span><span class="p">,</span> <span class="ss">significant: </span><span class="kp">true</span><span class="p">)</span> <span class="c1"># => 111</span> </code></pre> <button class="clipboard-button" data-clipboard-text="111.2345.to_fs(:rounded) # => 111.235 111.2345.to_fs(:rounded, precision: 2) # => 111.23 13.to_fs(:rounded, precision: 5) # => 13.00000 389.32314.to_fs(:rounded, precision: 0) # => 389 111.2345.to_fs(:rounded, significant: true) # => 111 ">Copy</button> </div> <p>Produce a string representation of a number as a human-readable number of bytes:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">123</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human_size</span><span class="p">)</span> <span class="c1"># => 123 Bytes</span> <span class="mi">1234</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human_size</span><span class="p">)</span> <span class="c1"># => 1.21 KB</span> <span class="mi">12345</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human_size</span><span class="p">)</span> <span class="c1"># => 12.1 KB</span> <span class="mi">1234567</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human_size</span><span class="p">)</span> <span class="c1"># => 1.18 MB</span> <span class="mi">1234567890</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human_size</span><span class="p">)</span> <span class="c1"># => 1.15 GB</span> <span class="mi">1234567890123</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human_size</span><span class="p">)</span> <span class="c1"># => 1.12 TB</span> <span class="mi">1234567890123456</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human_size</span><span class="p">)</span> <span class="c1"># => 1.1 PB</span> <span class="mi">1234567890123456789</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human_size</span><span class="p">)</span> <span class="c1"># => 1.07 EB</span> </code></pre> <button class="clipboard-button" data-clipboard-text="123.to_fs(:human_size) # => 123 Bytes 1234.to_fs(:human_size) # => 1.21 KB 12345.to_fs(:human_size) # => 12.1 KB 1234567.to_fs(:human_size) # => 1.18 MB 1234567890.to_fs(:human_size) # => 1.15 GB 1234567890123.to_fs(:human_size) # => 1.12 TB 1234567890123456.to_fs(:human_size) # => 1.1 PB 1234567890123456789.to_fs(:human_size) # => 1.07 EB ">Copy</button> </div> <p>Produce a string representation of a number in human-readable words:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">123</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human</span><span class="p">)</span> <span class="c1"># => "123"</span> <span class="mi">1234</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human</span><span class="p">)</span> <span class="c1"># => "1.23 Thousand"</span> <span class="mi">12345</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human</span><span class="p">)</span> <span class="c1"># => "12.3 Thousand"</span> <span class="mi">1234567</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human</span><span class="p">)</span> <span class="c1"># => "1.23 Million"</span> <span class="mi">1234567890</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human</span><span class="p">)</span> <span class="c1"># => "1.23 Billion"</span> <span class="mi">1234567890123</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human</span><span class="p">)</span> <span class="c1"># => "1.23 Trillion"</span> <span class="mi">1234567890123456</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:human</span><span class="p">)</span> <span class="c1"># => "1.23 Quadrillion"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="123.to_fs(:human) # => "123" 1234.to_fs(:human) # => "1.23 Thousand" 12345.to_fs(:human) # => "12.3 Thousand" 1234567.to_fs(:human) # => "1.23 Million" 1234567890.to_fs(:human) # => "1.23 Billion" 1234567890123.to_fs(:human) # => "1.23 Trillion" 1234567890123456.to_fs(:human) # => "1.23 Quadrillion" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/numeric/conversions.rb">active_support/core_ext/numeric/conversions.rb</a></code>.</p></div><h2 id="extensions-to-integer"><a class="anchorlink" href="#extensions-to-integer" data-turbo="false"><span>8</span> Extensions to <code>Integer</code></a></h2><h3 id="multiple-of-questionmark"><a class="anchorlink" href="#multiple-of-questionmark" data-turbo="false"><span>8.1</span> <code>multiple_of?</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Integer.html#method-i-multiple_of-3F"><code>multiple_of?</code></a> tests whether an integer is multiple of the argument:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">2</span><span class="p">.</span><span class="nf">multiple_of?</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => true</span> <span class="mi">1</span><span class="p">.</span><span class="nf">multiple_of?</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="2.multiple_of?(1) # => true 1.multiple_of?(2) # => false ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/integer/multiple.rb">active_support/core_ext/integer/multiple.rb</a></code>.</p></div><h3 id="ordinal"><a class="anchorlink" href="#ordinal" data-turbo="false"><span>8.2</span> <code>ordinal</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Integer.html#method-i-ordinal"><code>ordinal</code></a> returns the ordinal suffix string corresponding to the receiver integer:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">1</span><span class="p">.</span><span class="nf">ordinal</span> <span class="c1"># => "st"</span> <span class="mi">2</span><span class="p">.</span><span class="nf">ordinal</span> <span class="c1"># => "nd"</span> <span class="mi">53</span><span class="p">.</span><span class="nf">ordinal</span> <span class="c1"># => "rd"</span> <span class="mi">2009</span><span class="p">.</span><span class="nf">ordinal</span> <span class="c1"># => "th"</span> <span class="o">-</span><span class="mi">21</span><span class="p">.</span><span class="nf">ordinal</span> <span class="c1"># => "st"</span> <span class="o">-</span><span class="mi">134</span><span class="p">.</span><span class="nf">ordinal</span> <span class="c1"># => "th"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="1.ordinal # => "st" 2.ordinal # => "nd" 53.ordinal # => "rd" 2009.ordinal # => "th" -21.ordinal # => "st" -134.ordinal # => "th" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/integer/inflections.rb">active_support/core_ext/integer/inflections.rb</a></code>.</p></div><h3 id="ordinalize"><a class="anchorlink" href="#ordinalize" data-turbo="false"><span>8.3</span> <code>ordinalize</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Integer.html#method-i-ordinalize"><code>ordinalize</code></a> returns the ordinal string corresponding to the receiver integer. In comparison, note that the <code>ordinal</code> method returns <strong>only</strong> the suffix string.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="mi">1</span><span class="p">.</span><span class="nf">ordinalize</span> <span class="c1"># => "1st"</span> <span class="mi">2</span><span class="p">.</span><span class="nf">ordinalize</span> <span class="c1"># => "2nd"</span> <span class="mi">53</span><span class="p">.</span><span class="nf">ordinalize</span> <span class="c1"># => "53rd"</span> <span class="mi">2009</span><span class="p">.</span><span class="nf">ordinalize</span> <span class="c1"># => "2009th"</span> <span class="o">-</span><span class="mi">21</span><span class="p">.</span><span class="nf">ordinalize</span> <span class="c1"># => "-21st"</span> <span class="o">-</span><span class="mi">134</span><span class="p">.</span><span class="nf">ordinalize</span> <span class="c1"># => "-134th"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="1.ordinalize # => "1st" 2.ordinalize # => "2nd" 53.ordinalize # => "53rd" 2009.ordinalize # => "2009th" -21.ordinalize # => "-21st" -134.ordinalize # => "-134th" ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/integer/inflections.rb">active_support/core_ext/integer/inflections.rb</a></code>.</p></div><h3 id="extensions-to-integer-time"><a class="anchorlink" href="#extensions-to-integer-time" data-turbo="false"><span>8.4</span> Time</a></h3><p>The following methods:</p> <ul> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Integer.html#method-i-months"><code>months</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Integer.html#method-i-years"><code>years</code></a></li> </ul> <p>enable time declarations and calculations, like <code>4.months + 5.years</code>. Their return values can also be added to or subtracted from Time objects.</p><p>These methods can be combined with <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Duration.html#method-i-from_now"><code>from_now</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Duration.html#method-i-ago"><code>ago</code></a>, etc, for precise date calculations. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># equivalent to Time.current.advance(months: 1)</span> <span class="mi">1</span><span class="p">.</span><span class="nf">month</span><span class="p">.</span><span class="nf">from_now</span> <span class="c1"># equivalent to Time.current.advance(years: 2)</span> <span class="mi">2</span><span class="p">.</span><span class="nf">years</span><span class="p">.</span><span class="nf">from_now</span> <span class="c1"># equivalent to Time.current.advance(months: 4, years: 5)</span> <span class="p">(</span><span class="mi">4</span><span class="p">.</span><span class="nf">months</span> <span class="o">+</span> <span class="mi">5</span><span class="p">.</span><span class="nf">years</span><span class="p">).</span><span class="nf">from_now</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# equivalent to Time.current.advance(months: 1) 1.month.from_now # equivalent to Time.current.advance(years: 2) 2.years.from_now # equivalent to Time.current.advance(months: 4, years: 5) (4.months + 5.years).from_now ">Copy</button> </div> <div class="interstitial warning"><p>For other durations please refer to the time extensions to <code>Numeric</code>.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/integer/time.rb">active_support/core_ext/integer/time.rb</a></code>.</p></div><h2 id="extensions-to-bigdecimal"><a class="anchorlink" href="#extensions-to-bigdecimal" data-turbo="false"><span>9</span> Extensions to <code>BigDecimal</code></a></h2><h3 id="to-s"><a class="anchorlink" href="#to-s" data-turbo="false"><span>9.1</span> <code>to_s</code></a></h3><p>The method <code>to_s</code> provides a default specifier of "F". This means that a simple call to <code>to_s</code> will result in floating-point representation instead of engineering notation:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">BigDecimal</span><span class="p">(</span><span class="mf">5.00</span><span class="p">,</span> <span class="mi">6</span><span class="p">).</span><span class="nf">to_s</span> <span class="c1"># => "5.0"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="BigDecimal(5.00, 6).to_s # => "5.0" ">Copy</button> </div> <p>Engineering notation is still supported:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">BigDecimal</span><span class="p">(</span><span class="mf">5.00</span><span class="p">,</span> <span class="mi">6</span><span class="p">).</span><span class="nf">to_s</span><span class="p">(</span><span class="s2">"e"</span><span class="p">)</span> <span class="c1"># => "0.5E1"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="BigDecimal(5.00, 6).to_s("e") # => "0.5E1" ">Copy</button> </div> <h2 id="extensions-to-enumerable"><a class="anchorlink" href="#extensions-to-enumerable" data-turbo="false"><span>10</span> Extensions to <code>Enumerable</code></a></h2><h3 id="index-by"><a class="anchorlink" href="#index-by" data-turbo="false"><span>10.1</span> <code>index_by</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Enumerable.html#method-i-index_by"><code>index_by</code></a> generates a hash with the elements of an enumerable indexed by some key.</p><p>It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">invoices</span><span class="p">.</span><span class="nf">index_by</span><span class="p">(</span><span class="o">&</span><span class="ss">:number</span><span class="p">)</span> <span class="c1"># => {"2009-032" => <Invoice ...>, "2009-008" => <Invoice ...>, ...}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="invoices.index_by(&:number) # => {"2009-032" => <Invoice ...>, "2009-008" => <Invoice ...>, ...} ">Copy</button> </div> <div class="interstitial warning"><p>Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/enumerable.rb">active_support/core_ext/enumerable.rb</a></code>.</p></div><h3 id="index-with"><a class="anchorlink" href="#index-with" data-turbo="false"><span>10.2</span> <code>index_with</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Enumerable.html#method-i-index_with"><code>index_with</code></a> generates a hash with the elements of an enumerable as keys. The value is either a passed default or returned in a block.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">post</span> <span class="o">=</span> <span class="no">Post</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="ss">title: </span><span class="s2">"hey there"</span><span class="p">,</span> <span class="ss">body: </span><span class="s2">"what's up?"</span><span class="p">)</span> <span class="sx">%i( title body )</span><span class="p">.</span><span class="nf">index_with</span> <span class="p">{</span> <span class="o">|</span><span class="n">attr_name</span><span class="o">|</span> <span class="n">post</span><span class="p">.</span><span class="nf">public_send</span><span class="p">(</span><span class="n">attr_name</span><span class="p">)</span> <span class="p">}</span> <span class="c1"># => { title: "hey there", body: "what's up?" }</span> <span class="no">WEEKDAYS</span><span class="p">.</span><span class="nf">index_with</span><span class="p">(</span><span class="no">Interval</span><span class="p">.</span><span class="nf">all_day</span><span class="p">)</span> <span class="c1"># => { monday: [ 0, 1440 ], … }</span> </code></pre> <button class="clipboard-button" data-clipboard-text="post = Post.new(title: "hey there", body: "what's up?") %i( title body ).index_with { |attr_name| post.public_send(attr_name) } # => { title: "hey there", body: "what's up?" } WEEKDAYS.index_with(Interval.all_day) # => { monday: [ 0, 1440 ], … } ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/enumerable.rb">active_support/core_ext/enumerable.rb</a></code>.</p></div><h3 id="many-questionmark"><a class="anchorlink" href="#many-questionmark" data-turbo="false"><span>10.3</span> <code>many?</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Enumerable.html#method-i-many-3F"><code>many?</code></a> is shorthand for <code>collection.size > 1</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp"><%</span> <span class="k">if</span> <span class="n">pages</span><span class="p">.</span><span class="nf">many?</span> <span class="cp">%></span> <span class="cp"><%=</span> <span class="n">pagination_links</span> <span class="cp">%></span> <span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% if pages.many? %> <%= pagination_links %> <% end %> ">Copy</button> </div> <p>If an optional block is given, <code>many?</code> only takes into account those elements that return true:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="vi">@see_more</span> <span class="o">=</span> <span class="n">videos</span><span class="p">.</span><span class="nf">many?</span> <span class="p">{</span> <span class="o">|</span><span class="n">video</span><span class="o">|</span> <span class="n">video</span><span class="p">.</span><span class="nf">category</span> <span class="o">==</span> <span class="n">params</span><span class="p">[</span><span class="ss">:category</span><span class="p">]</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="@see_more = videos.many? { |video| video.category == params[:category] } ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/enumerable.rb">active_support/core_ext/enumerable.rb</a></code>.</p></div><h3 id="exclude-questionmark"><a class="anchorlink" href="#exclude-questionmark" data-turbo="false"><span>10.4</span> <code>exclude?</code></a></h3><p>The predicate <a href="https://api.rubyonrails.org/v8.0.0/classes/Enumerable.html#method-i-exclude-3F"><code>exclude?</code></a> tests whether a given object does <strong>not</strong> belong to the collection. It is the negation of the built-in <code>include?</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">to_visit</span> <span class="o"><<</span> <span class="n">node</span> <span class="k">if</span> <span class="n">visited</span><span class="p">.</span><span class="nf">exclude?</span><span class="p">(</span><span class="n">node</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="to_visit << node if visited.exclude?(node) ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/enumerable.rb">active_support/core_ext/enumerable.rb</a></code>.</p></div><h3 id="including"><a class="anchorlink" href="#including" data-turbo="false"><span>10.5</span> <code>including</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Enumerable.html#method-i-including"><code>including</code></a> returns a new enumerable that includes the passed elements:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span> <span class="p">].</span><span class="nf">including</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span> <span class="c1"># => [ 1, 2, 3, 4, 5 ]</span> <span class="p">[</span><span class="s2">"David"</span><span class="p">,</span> <span class="s2">"Rafael"</span><span class="p">].</span><span class="nf">including</span> <span class="sx">%w[ Aaron Todd ]</span> <span class="c1"># => ["David", "Rafael", "Aaron", "Todd"]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[ 1, 2, 3 ].including(4, 5) # => [ 1, 2, 3, 4, 5 ] ["David", "Rafael"].including %w[ Aaron Todd ] # => ["David", "Rafael", "Aaron", "Todd"] ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/enumerable.rb">active_support/core_ext/enumerable.rb</a></code>.</p></div><h3 id="excluding"><a class="anchorlink" href="#excluding" data-turbo="false"><span>10.6</span> <code>excluding</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Enumerable.html#method-i-excluding"><code>excluding</code></a> returns a copy of an enumerable with the specified elements removed:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="s2">"David"</span><span class="p">,</span> <span class="s2">"Rafael"</span><span class="p">,</span> <span class="s2">"Aaron"</span><span class="p">,</span> <span class="s2">"Todd"</span><span class="p">].</span><span class="nf">excluding</span><span class="p">(</span><span class="s2">"Aaron"</span><span class="p">,</span> <span class="s2">"Todd"</span><span class="p">)</span> <span class="c1"># => ["David", "Rafael"]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"] ">Copy</button> </div> <p><code>excluding</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/Enumerable.html#method-i-without"><code>without</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/enumerable.rb">active_support/core_ext/enumerable.rb</a></code>.</p></div><h3 id="pluck"><a class="anchorlink" href="#pluck" data-turbo="false"><span>10.7</span> <code>pluck</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Enumerable.html#method-i-pluck"><code>pluck</code></a> extracts the given key from each element:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[{</span> <span class="ss">name: </span><span class="s2">"David"</span> <span class="p">},</span> <span class="p">{</span> <span class="ss">name: </span><span class="s2">"Rafael"</span> <span class="p">},</span> <span class="p">{</span> <span class="ss">name: </span><span class="s2">"Aaron"</span> <span class="p">}].</span><span class="nf">pluck</span><span class="p">(</span><span class="ss">:name</span><span class="p">)</span> <span class="c1"># => ["David", "Rafael", "Aaron"]</span> <span class="p">[{</span> <span class="ss">id: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">name: </span><span class="s2">"David"</span> <span class="p">},</span> <span class="p">{</span> <span class="ss">id: </span><span class="mi">2</span><span class="p">,</span> <span class="ss">name: </span><span class="s2">"Rafael"</span> <span class="p">}].</span><span class="nf">pluck</span><span class="p">(</span><span class="ss">:id</span><span class="p">,</span> <span class="ss">:name</span><span class="p">)</span> <span class="c1"># => [[1, "David"], [2, "Rafael"]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name) # => ["David", "Rafael", "Aaron"] [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name) # => [[1, "David"], [2, "Rafael"]] ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/enumerable.rb">active_support/core_ext/enumerable.rb</a></code>.</p></div><h3 id="pick"><a class="anchorlink" href="#pick" data-turbo="false"><span>10.8</span> <code>pick</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Enumerable.html#method-i-pick"><code>pick</code></a> extracts the given key from the first element:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[{</span> <span class="ss">name: </span><span class="s2">"David"</span> <span class="p">},</span> <span class="p">{</span> <span class="ss">name: </span><span class="s2">"Rafael"</span> <span class="p">},</span> <span class="p">{</span> <span class="ss">name: </span><span class="s2">"Aaron"</span> <span class="p">}].</span><span class="nf">pick</span><span class="p">(</span><span class="ss">:name</span><span class="p">)</span> <span class="c1"># => "David"</span> <span class="p">[{</span> <span class="ss">id: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">name: </span><span class="s2">"David"</span> <span class="p">},</span> <span class="p">{</span> <span class="ss">id: </span><span class="mi">2</span><span class="p">,</span> <span class="ss">name: </span><span class="s2">"Rafael"</span> <span class="p">}].</span><span class="nf">pick</span><span class="p">(</span><span class="ss">:id</span><span class="p">,</span> <span class="ss">:name</span><span class="p">)</span> <span class="c1"># => [1, "David"]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pick(:name) # => "David" [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pick(:id, :name) # => [1, "David"] ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/enumerable.rb">active_support/core_ext/enumerable.rb</a></code>.</p></div><h2 id="extensions-to-array"><a class="anchorlink" href="#extensions-to-array" data-turbo="false"><span>11</span> Extensions to <code>Array</code></a></h2><h3 id="accessing"><a class="anchorlink" href="#accessing" data-turbo="false"><span>11.1</span> Accessing</a></h3><p>Active Support augments the API of arrays to ease certain ways of accessing them. For example, <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-to"><code>to</code></a> returns the subarray of elements up to the one at the passed index:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="sx">%w(a b c d)</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => ["a", "b", "c"]</span> <span class="p">[].</span><span class="nf">to</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span> <span class="c1"># => []</span> </code></pre> <button class="clipboard-button" data-clipboard-text="%w(a b c d).to(2) # => ["a", "b", "c"] [].to(7) # => [] ">Copy</button> </div> <p>Similarly, <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-from"><code>from</code></a> returns the tail from the element at the passed index to the end. If the index is greater than the length of the array, it returns an empty array.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="sx">%w(a b c d)</span><span class="p">.</span><span class="nf">from</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => ["c", "d"]</span> <span class="sx">%w(a b c d)</span><span class="p">.</span><span class="nf">from</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># => []</span> <span class="p">[].</span><span class="nf">from</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => []</span> </code></pre> <button class="clipboard-button" data-clipboard-text="%w(a b c d).from(2) # => ["c", "d"] %w(a b c d).from(10) # => [] [].from(0) # => [] ">Copy</button> </div> <p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-including"><code>including</code></a> returns a new array that includes the passed elements:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span> <span class="p">].</span><span class="nf">including</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span> <span class="c1"># => [ 1, 2, 3, 4, 5 ]</span> <span class="p">[</span> <span class="p">[</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span> <span class="p">]</span> <span class="p">].</span><span class="nf">including</span><span class="p">([</span> <span class="p">[</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span> <span class="p">]</span> <span class="p">])</span> <span class="c1"># => [ [ 0, 1 ], [ 1, 0 ] ]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[ 1, 2, 3 ].including(4, 5) # => [ 1, 2, 3, 4, 5 ] [ [ 0, 1 ] ].including([ [ 1, 0 ] ]) # => [ [ 0, 1 ], [ 1, 0 ] ] ">Copy</button> </div> <p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-excluding"><code>excluding</code></a> returns a copy of the Array excluding the specified elements. This is an optimization of <code>Enumerable#excluding</code> that uses <code>Array#-</code> instead of <code>Array#reject</code> for performance reasons.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="s2">"David"</span><span class="p">,</span> <span class="s2">"Rafael"</span><span class="p">,</span> <span class="s2">"Aaron"</span><span class="p">,</span> <span class="s2">"Todd"</span><span class="p">].</span><span class="nf">excluding</span><span class="p">(</span><span class="s2">"Aaron"</span><span class="p">,</span> <span class="s2">"Todd"</span><span class="p">)</span> <span class="c1"># => ["David", "Rafael"]</span> <span class="p">[</span> <span class="p">[</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span> <span class="p">],</span> <span class="p">[</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span> <span class="p">]</span> <span class="p">].</span><span class="nf">excluding</span><span class="p">([</span> <span class="p">[</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span> <span class="p">]</span> <span class="p">])</span> <span class="c1"># => [ [ 0, 1 ] ]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"] [ [ 0, 1 ], [ 1, 0 ] ].excluding([ [ 1, 0 ] ]) # => [ [ 0, 1 ] ] ">Copy</button> </div> <p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-second"><code>second</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-third"><code>third</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-fourth"><code>fourth</code></a>, and <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-fifth"><code>fifth</code></a> return the corresponding element, as do <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-second_to_last"><code>second_to_last</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-third_to_last"><code>third_to_last</code></a> (<code>first</code> and <code>last</code> are built-in). Thanks to social wisdom and positive constructiveness all around, <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-forty_two"><code>forty_two</code></a> is also available.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="sx">%w(a b c d)</span><span class="p">.</span><span class="nf">third</span> <span class="c1"># => "c"</span> <span class="sx">%w(a b c d)</span><span class="p">.</span><span class="nf">fifth</span> <span class="c1"># => nil</span> </code></pre> <button class="clipboard-button" data-clipboard-text="%w(a b c d).third # => "c" %w(a b c d).fifth # => nil ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/access.rb">active_support/core_ext/array/access.rb</a></code>.</p></div><h3 id="extensions-to-array-extracting"><a class="anchorlink" href="#extensions-to-array-extracting" data-turbo="false"><span>11.2</span> Extracting</a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-extract-21"><code>extract!</code></a> removes and returns the elements for which the block returns a true value. If no block is given, an Enumerator is returned instead.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">numbers</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">]</span> <span class="n">odd_numbers</span> <span class="o">=</span> <span class="n">numbers</span><span class="p">.</span><span class="nf">extract!</span> <span class="p">{</span> <span class="o">|</span><span class="n">number</span><span class="o">|</span> <span class="n">number</span><span class="p">.</span><span class="nf">odd?</span> <span class="p">}</span> <span class="c1"># => [1, 3, 5, 7, 9]</span> <span class="n">numbers</span> <span class="c1"># => [0, 2, 4, 6, 8]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9] numbers # => [0, 2, 4, 6, 8] ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/extract.rb">active_support/core_ext/array/extract.rb</a></code>.</p></div><h3 id="options-extraction"><a class="anchorlink" href="#options-extraction" data-turbo="false"><span>11.3</span> Options Extraction</a></h3><p>When the last argument in a method call is a hash, except perhaps for a <code>&block</code> argument, Ruby allows you to omit the brackets:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">User</span><span class="p">.</span><span class="nf">exists?</span><span class="p">(</span><span class="ss">email: </span><span class="n">params</span><span class="p">[</span><span class="ss">:email</span><span class="p">])</span> </code></pre> <button class="clipboard-button" data-clipboard-text="User.exists?(email: params[:email]) ">Copy</button> </div> <p>That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.</p><p>If a method expects a variable number of arguments and uses <code>*</code> in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.</p><p>In those cases, you may give an options hash a distinguished treatment with <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-extract_options-21"><code>extract_options!</code></a>. This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash.</p><p>Let's see for example the definition of the <code>caches_action</code> controller macro:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">caches_action</span><span class="p">(</span><span class="o">*</span><span class="n">actions</span><span class="p">)</span> <span class="k">return</span> <span class="k">unless</span> <span class="n">cache_configured?</span> <span class="n">options</span> <span class="o">=</span> <span class="n">actions</span><span class="p">.</span><span class="nf">extract_options!</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def caches_action(*actions) return unless cache_configured? options = actions.extract_options! # ... end ">Copy</button> </div> <p>This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to <code>extract_options!</code> you obtain the options hash and remove it from <code>actions</code> in a simple and explicit way.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/extract_options.rb">active_support/core_ext/array/extract_options.rb</a></code>.</p></div><h3 id="extensions-to-array-conversions"><a class="anchorlink" href="#extensions-to-array-conversions" data-turbo="false"><span>11.4</span> Conversions</a></h3><h4 id="to-sentence"><a class="anchorlink" href="#to-sentence" data-turbo="false"><span>11.4.1</span> <code>to_sentence</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-to_sentence"><code>to_sentence</code></a> turns an array into a string containing a sentence that enumerates its items:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="sx">%w()</span><span class="p">.</span><span class="nf">to_sentence</span> <span class="c1"># => ""</span> <span class="sx">%w(Earth)</span><span class="p">.</span><span class="nf">to_sentence</span> <span class="c1"># => "Earth"</span> <span class="sx">%w(Earth Wind)</span><span class="p">.</span><span class="nf">to_sentence</span> <span class="c1"># => "Earth and Wind"</span> <span class="sx">%w(Earth Wind Fire)</span><span class="p">.</span><span class="nf">to_sentence</span> <span class="c1"># => "Earth, Wind, and Fire"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="%w().to_sentence # => "" %w(Earth).to_sentence # => "Earth" %w(Earth Wind).to_sentence # => "Earth and Wind" %w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire" ">Copy</button> </div> <p>This method accepts three options:</p> <ul> <li><code>:two_words_connector</code>: What is used for arrays of length 2. Default is " and ".</li> <li><code>:words_connector</code>: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".</li> <li><code>:last_word_connector</code>: What is used to join the last items of an array with 3 or more elements. Default is ", and ".</li> </ul> <p>The defaults for these options can be localized, their keys are:</p> <div class="table-wrapper"><table><thead> <tr> <th>Option</th> <th>I18n key</th> </tr> </thead><tbody> <tr> <td><code>:two_words_connector</code></td> <td><code>support.array.two_words_connector</code></td> </tr> <tr> <td><code>:words_connector</code></td> <td><code>support.array.words_connector</code></td> </tr> <tr> <td><code>:last_word_connector</code></td> <td><code>support.array.last_word_connector</code></td> </tr> </tbody></table></div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/conversions.rb">active_support/core_ext/array/conversions.rb</a></code>.</p></div><h4 id="extensions-to-array-conversions-to-fs"><a class="anchorlink" href="#extensions-to-array-conversions-to-fs" data-turbo="false"><span>11.4.2</span> <code>to_fs</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-to_fs"><code>to_fs</code></a> acts like <code>to_s</code> by default.</p><p>If the array contains items that respond to <code>id</code>, however, the symbol <code>:db</code> may be passed as argument. That's typically used with collections of Active Record objects. Returned strings are:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[].</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:db</span><span class="p">)</span> <span class="c1"># => "null"</span> <span class="p">[</span><span class="n">user</span><span class="p">].</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:db</span><span class="p">)</span> <span class="c1"># => "8456"</span> <span class="n">invoice</span><span class="p">.</span><span class="nf">lines</span><span class="p">.</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:db</span><span class="p">)</span> <span class="c1"># => "23,567,556,12"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[].to_fs(:db) # => "null" [user].to_fs(:db) # => "8456" invoice.lines.to_fs(:db) # => "23,567,556,12" ">Copy</button> </div> <p>Integers in the example above are supposed to come from the respective calls to <code>id</code>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/conversions.rb">active_support/core_ext/array/conversions.rb</a></code>.</p></div><h4 id="extensions-to-array-conversions-to-xml"><a class="anchorlink" href="#extensions-to-array-conversions-to-xml" data-turbo="false"><span>11.4.3</span> <code>to_xml</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-to_xml"><code>to_xml</code></a> returns a string containing an XML representation of its receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Contributor</span><span class="p">.</span><span class="nf">limit</span><span class="p">(</span><span class="mi">2</span><span class="p">).</span><span class="nf">order</span><span class="p">(</span><span class="ss">:rank</span><span class="p">).</span><span class="nf">to_xml</span> <span class="c1"># =></span> <span class="c1"># <?xml version="1.0" encoding="UTF-8"?></span> <span class="c1"># <contributors type="array"></span> <span class="c1"># <contributor></span> <span class="c1"># <id type="integer">4356</id></span> <span class="c1"># <name>Jeremy Kemper</name></span> <span class="c1"># <rank type="integer">1</rank></span> <span class="c1"># <url-id>jeremy-kemper</url-id></span> <span class="c1"># </contributor></span> <span class="c1"># <contributor></span> <span class="c1"># <id type="integer">4404</id></span> <span class="c1"># <name>David Heinemeier Hansson</name></span> <span class="c1"># <rank type="integer">2</rank></span> <span class="c1"># <url-id>david-heinemeier-hansson</url-id></span> <span class="c1"># </contributor></span> <span class="c1"># </contributors></span> </code></pre> <button class="clipboard-button" data-clipboard-text="Contributor.limit(2).order(:rank).to_xml # => # <?xml version="1.0" encoding="UTF-8"?> # <contributors type="array"> # <contributor> # <id type="integer">4356</id> # <name>Jeremy Kemper</name> # <rank type="integer">1</rank> # <url-id>jeremy-kemper</url-id> # </contributor> # <contributor> # <id type="integer">4404</id> # <name>David Heinemeier Hansson</name> # <rank type="integer">2</rank> # <url-id>david-heinemeier-hansson</url-id> # </contributor> # </contributors> ">Copy</button> </div> <p>To do so it sends <code>to_xml</code> to every item in turn, and collects the results under a root node. All items must respond to <code>to_xml</code>, an exception is raised otherwise.</p><p>By default, the name of the root element is the underscored and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with <code>is_a?</code>) and they are not hashes. In the example above that's "contributors".</p><p>If there's any element that does not belong to the type of the first one the root node becomes "objects":</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="no">Contributor</span><span class="p">.</span><span class="nf">first</span><span class="p">,</span> <span class="no">Commit</span><span class="p">.</span><span class="nf">first</span><span class="p">].</span><span class="nf">to_xml</span> <span class="c1"># =></span> <span class="c1"># <?xml version="1.0" encoding="UTF-8"?></span> <span class="c1"># <objects type="array"></span> <span class="c1"># <object></span> <span class="c1"># <id type="integer">4583</id></span> <span class="c1"># <name>Aaron Batalion</name></span> <span class="c1"># <rank type="integer">53</rank></span> <span class="c1"># <url-id>aaron-batalion</url-id></span> <span class="c1"># </object></span> <span class="c1"># <object></span> <span class="c1"># <author>Joshua Peek</author></span> <span class="c1"># <authored-timestamp type="datetime">2009-09-02T16:44:36Z</authored-timestamp></span> <span class="c1"># <branch>origin/master</branch></span> <span class="c1"># <committed-timestamp type="datetime">2009-09-02T16:44:36Z</committed-timestamp></span> <span class="c1"># <committer>Joshua Peek</committer></span> <span class="c1"># <git-show nil="true"></git-show></span> <span class="c1"># <id type="integer">190316</id></span> <span class="c1"># <imported-from-svn type="boolean">false</imported-from-svn></span> <span class="c1"># <message>Kill AMo observing wrap_with_notifications since ARes was only using it</message></span> <span class="c1"># <sha1>723a47bfb3708f968821bc969a9a3fc873a3ed58</sha1></span> <span class="c1"># </object></span> <span class="c1"># </objects></span> </code></pre> <button class="clipboard-button" data-clipboard-text="[Contributor.first, Commit.first].to_xml # => # <?xml version="1.0" encoding="UTF-8"?> # <objects type="array"> # <object> # <id type="integer">4583</id> # <name>Aaron Batalion</name> # <rank type="integer">53</rank> # <url-id>aaron-batalion</url-id> # </object> # <object> # <author>Joshua Peek</author> # <authored-timestamp type="datetime">2009-09-02T16:44:36Z</authored-timestamp> # <branch>origin/master</branch> # <committed-timestamp type="datetime">2009-09-02T16:44:36Z</committed-timestamp> # <committer>Joshua Peek</committer> # <git-show nil="true"></git-show> # <id type="integer">190316</id> # <imported-from-svn type="boolean">false</imported-from-svn> # <message>Kill AMo observing wrap_with_notifications since ARes was only using it</message> # <sha1>723a47bfb3708f968821bc969a9a3fc873a3ed58</sha1> # </object> # </objects> ">Copy</button> </div> <p>If the receiver is an array of hashes the root element is by default also "objects":</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[{</span> <span class="ss">a: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">b: </span><span class="mi">2</span> <span class="p">},</span> <span class="p">{</span> <span class="ss">c: </span><span class="mi">3</span> <span class="p">}].</span><span class="nf">to_xml</span> <span class="c1"># =></span> <span class="c1"># <?xml version="1.0" encoding="UTF-8"?></span> <span class="c1"># <objects type="array"></span> <span class="c1"># <object></span> <span class="c1"># <b type="integer">2</b></span> <span class="c1"># <a type="integer">1</a></span> <span class="c1"># </object></span> <span class="c1"># <object></span> <span class="c1"># <c type="integer">3</c></span> <span class="c1"># </object></span> <span class="c1"># </objects></span> </code></pre> <button class="clipboard-button" data-clipboard-text="[{ a: 1, b: 2 }, { c: 3 }].to_xml # => # <?xml version="1.0" encoding="UTF-8"?> # <objects type="array"> # <object> # <b type="integer">2</b> # <a type="integer">1</a> # </object> # <object> # <c type="integer">3</c> # </object> # </objects> ">Copy</button> </div> <div class="interstitial warning"><p>If the collection is empty the root element is by default "nil-classes". That's a gotcha, for example the root element of the list of contributors above would not be "contributors" if the collection was empty, but "nil-classes". You may use the <code>:root</code> option to ensure a consistent root element.</p></div><p>The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "object". The option <code>:children</code> allows you to set these node names.</p><p>The default XML builder is a fresh instance of <code>Builder::XmlMarkup</code>. You can configure your own builder via the <code>:builder</code> option. The method also accepts options like <code>:dasherize</code> and friends, they are forwarded to the builder:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Contributor</span><span class="p">.</span><span class="nf">limit</span><span class="p">(</span><span class="mi">2</span><span class="p">).</span><span class="nf">order</span><span class="p">(</span><span class="ss">:rank</span><span class="p">).</span><span class="nf">to_xml</span><span class="p">(</span><span class="ss">skip_types: </span><span class="kp">true</span><span class="p">)</span> <span class="c1"># =></span> <span class="c1"># <?xml version="1.0" encoding="UTF-8"?></span> <span class="c1"># <contributors></span> <span class="c1"># <contributor></span> <span class="c1"># <id>4356</id></span> <span class="c1"># <name>Jeremy Kemper</name></span> <span class="c1"># <rank>1</rank></span> <span class="c1"># <url-id>jeremy-kemper</url-id></span> <span class="c1"># </contributor></span> <span class="c1"># <contributor></span> <span class="c1"># <id>4404</id></span> <span class="c1"># <name>David Heinemeier Hansson</name></span> <span class="c1"># <rank>2</rank></span> <span class="c1"># <url-id>david-heinemeier-hansson</url-id></span> <span class="c1"># </contributor></span> <span class="c1"># </contributors></span> </code></pre> <button class="clipboard-button" data-clipboard-text="Contributor.limit(2).order(:rank).to_xml(skip_types: true) # => # <?xml version="1.0" encoding="UTF-8"?> # <contributors> # <contributor> # <id>4356</id> # <name>Jeremy Kemper</name> # <rank>1</rank> # <url-id>jeremy-kemper</url-id> # </contributor> # <contributor> # <id>4404</id> # <name>David Heinemeier Hansson</name> # <rank>2</rank> # <url-id>david-heinemeier-hansson</url-id> # </contributor> # </contributors> ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/conversions.rb">active_support/core_ext/array/conversions.rb</a></code>.</p></div><h3 id="wrapping"><a class="anchorlink" href="#wrapping" data-turbo="false"><span>11.5</span> Wrapping</a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-c-wrap"><code>Array.wrap</code></a> wraps its argument in an array unless it is already an array (or array-like).</p><p>Specifically:</p> <ul> <li>If the argument is <code>nil</code> an empty array is returned.</li> <li>Otherwise, if the argument responds to <code>to_ary</code> it is invoked, and if the value of <code>to_ary</code> is not <code>nil</code>, it is returned.</li> <li>Otherwise, an array with the argument as its single element is returned.</li> </ul> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Array</span><span class="p">.</span><span class="nf">wrap</span><span class="p">(</span><span class="kp">nil</span><span class="p">)</span> <span class="c1"># => []</span> <span class="no">Array</span><span class="p">.</span><span class="nf">wrap</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span> <span class="c1"># => [1, 2, 3]</span> <span class="no">Array</span><span class="p">.</span><span class="nf">wrap</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => [0]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Array.wrap(nil) # => [] Array.wrap([1, 2, 3]) # => [1, 2, 3] Array.wrap(0) # => [0] ">Copy</button> </div> <p>This method is similar in purpose to <code>Kernel#Array</code>, but there are some differences:</p> <ul> <li>If the argument responds to <code>to_ary</code> the method is invoked. <code>Kernel#Array</code> moves on to try <code>to_a</code> if the returned value is <code>nil</code>, but <code>Array.wrap</code> returns an array with the argument as its single element right away.</li> <li>If the returned value from <code>to_ary</code> is neither <code>nil</code> nor an <code>Array</code> object, <code>Kernel#Array</code> raises an exception, while <code>Array.wrap</code> does not, it just returns the value.</li> <li>It does not call <code>to_a</code> on the argument, if the argument does not respond to <code>to_ary</code> it returns an array with the argument as its single element.</li> </ul> <p>The last point is particularly worth comparing for some enumerables:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Array</span><span class="p">.</span><span class="nf">wrap</span><span class="p">(</span><span class="ss">foo: :bar</span><span class="p">)</span> <span class="c1"># => [{:foo=>:bar}]</span> <span class="no">Array</span><span class="p">(</span><span class="ss">foo: :bar</span><span class="p">)</span> <span class="c1"># => [[:foo, :bar]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Array.wrap(foo: :bar) # => [{:foo=>:bar}] Array(foo: :bar) # => [[:foo, :bar]] ">Copy</button> </div> <p>There's also a related idiom that uses the splat operator:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="o">*</span><span class="n">object</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[*object] ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/wrap.rb">active_support/core_ext/array/wrap.rb</a></code>.</p></div><h3 id="duplicating"><a class="anchorlink" href="#duplicating" data-turbo="false"><span>11.6</span> Duplicating</a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-deep_dup"><code>Array#deep_dup</code></a> duplicates itself and all objects inside recursively with the Active Support method <code>Object#deep_dup</code>. It works like <code>Array#map</code>, sending <code>deep_dup</code> method to each object inside.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">array</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]]</span> <span class="nb">dup</span> <span class="o">=</span> <span class="n">array</span><span class="p">.</span><span class="nf">deep_dup</span> <span class="nb">dup</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="mi">4</span> <span class="n">array</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">2</span><span class="p">]</span> <span class="o">==</span> <span class="kp">nil</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="array = [1, [2, 3]] dup = array.deep_dup dup[1][2] = 4 array[1][2] == nil # => true ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/deep_dup.rb">active_support/core_ext/object/deep_dup.rb</a></code>.</p></div><h3 id="grouping"><a class="anchorlink" href="#grouping" data-turbo="false"><span>11.7</span> Grouping</a></h3><h4 id="in-groups-of-number-fill-with-nil"><a class="anchorlink" href="#in-groups-of-number-fill-with-nil" data-turbo="false"><span>11.7.1</span> <code>in_groups_of(number, fill_with = nil)</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-in_groups_of"><code>in_groups_of</code></a> splits an array into consecutive groups of a certain size. It returns an array with the groups:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">].</span><span class="nf">in_groups_of</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => [[1, 2], [3, nil]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]] ">Copy</button> </div> <p>or yields them in turn if a block is passed:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp"><%</span> <span class="n">sample</span><span class="p">.</span><span class="nf">in_groups_of</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="o">|</span> <span class="cp">%></span> <span class="nt"><tr></span> <span class="nt"><td></span><span class="cp"><%=</span> <span class="n">a</span> <span class="cp">%></span><span class="nt"></td></span> <span class="nt"><td></span><span class="cp"><%=</span> <span class="n">b</span> <span class="cp">%></span><span class="nt"></td></span> <span class="nt"><td></span><span class="cp"><%=</span> <span class="n">c</span> <span class="cp">%></span><span class="nt"></td></span> <span class="nt"></tr></span> <span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% sample.in_groups_of(3) do |a, b, c| %> <tr> <td><%= a %></td> <td><%= b %></td> <td><%= c %></td> </tr> <% end %> ">Copy</button> </div> <p>The first example shows how <code>in_groups_of</code> fills the last group with as many <code>nil</code> elements as needed to have the requested size. You can change this padding value using the second optional argument:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">].</span><span class="nf">in_groups_of</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="c1"># => [[1, 2], [3, 0]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]] ">Copy</button> </div> <p>And you can tell the method not to fill the last group by passing <code>false</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">].</span><span class="nf">in_groups_of</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="kp">false</span><span class="p">)</span> <span class="c1"># => [[1, 2], [3]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]] ">Copy</button> </div> <p>As a consequence <code>false</code> can't be used as a padding value.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/grouping.rb">active_support/core_ext/array/grouping.rb</a></code>.</p></div><h4 id="in-groups-number-fill-with-nil"><a class="anchorlink" href="#in-groups-number-fill-with-nil" data-turbo="false"><span>11.7.2</span> <code>in_groups(number, fill_with = nil)</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-in_groups"><code>in_groups</code></a> splits an array into a certain number of groups. The method returns an array with the groups:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="sx">%w(1 2 3 4 5 6 7)</span><span class="p">.</span><span class="nf">in_groups</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="c1"># => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="%w(1 2 3 4 5 6 7).in_groups(3) # => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]] ">Copy</button> </div> <p>or yields them in turn if a block is passed:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="sx">%w(1 2 3 4 5 6 7)</span><span class="p">.</span><span class="nf">in_groups</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="p">{</span> <span class="o">|</span><span class="n">group</span><span class="o">|</span> <span class="nb">p</span> <span class="n">group</span> <span class="p">}</span> <span class="p">[</span><span class="s2">"1"</span><span class="p">,</span> <span class="s2">"2"</span><span class="p">,</span> <span class="s2">"3"</span><span class="p">]</span> <span class="p">[</span><span class="s2">"4"</span><span class="p">,</span> <span class="s2">"5"</span><span class="p">,</span> <span class="kp">nil</span><span class="p">]</span> <span class="p">[</span><span class="s2">"6"</span><span class="p">,</span> <span class="s2">"7"</span><span class="p">,</span> <span class="kp">nil</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="%w(1 2 3 4 5 6 7).in_groups(3) { |group| p group } ["1", "2", "3"] ["4", "5", nil] ["6", "7", nil] ">Copy</button> </div> <p>The examples above show that <code>in_groups</code> fills some groups with a trailing <code>nil</code> element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.</p><p>You can change this padding value using the second optional argument:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="sx">%w(1 2 3 4 5 6 7)</span><span class="p">.</span><span class="nf">in_groups</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s2">"0"</span><span class="p">)</span> <span class="c1"># => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="%w(1 2 3 4 5 6 7).in_groups(3, "0") # => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]] ">Copy</button> </div> <p>And you can tell the method not to fill the smaller groups by passing <code>false</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="sx">%w(1 2 3 4 5 6 7)</span><span class="p">.</span><span class="nf">in_groups</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="kp">false</span><span class="p">)</span> <span class="c1"># => [["1", "2", "3"], ["4", "5"], ["6", "7"]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="%w(1 2 3 4 5 6 7).in_groups(3, false) # => [["1", "2", "3"], ["4", "5"], ["6", "7"]] ">Copy</button> </div> <p>As a consequence <code>false</code> can't be used as a padding value.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/grouping.rb">active_support/core_ext/array/grouping.rb</a></code>.</p></div><h4 id="split-value-nil"><a class="anchorlink" href="#split-value-nil" data-turbo="false"><span>11.7.3</span> <code>split(value = nil)</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Array.html#method-i-split"><code>split</code></a> divides an array by a separator and returns the resulting chunks.</p><p>If a block is passed the separators are those elements of the array for which the block returns true:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">(</span><span class="o">-</span><span class="mi">5</span><span class="o">..</span><span class="mi">5</span><span class="p">).</span><span class="nf">to_a</span><span class="p">.</span><span class="nf">split</span> <span class="p">{</span> <span class="o">|</span><span class="n">i</span><span class="o">|</span> <span class="n">i</span><span class="p">.</span><span class="nf">multiple_of?</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="p">}</span> <span class="c1"># => [[-5], [-3, -2, -1], [1, 2, 3], [5]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="(-5..5).to_a.split { |i| i.multiple_of?(4) } # => [[-5], [-3, -2, -1], [1, 2, 3], [5]] ">Copy</button> </div> <p>Otherwise, the value received as argument, which defaults to <code>nil</code>, is the separator:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s2">"foo"</span><span class="p">,</span> <span class="s2">"bar"</span><span class="p">].</span><span class="nf">split</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => [[0], [-5], [], ["foo", "bar"]]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="[0, 1, -5, 1, 1, "foo", "bar"].split(1) # => [[0], [-5], [], ["foo", "bar"]] ">Copy</button> </div> <div class="interstitial info"><p>Observe in the previous example that consecutive separators result in empty arrays.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/array/grouping.rb">active_support/core_ext/array/grouping.rb</a></code>.</p></div><h2 id="extensions-to-hash"><a class="anchorlink" href="#extensions-to-hash" data-turbo="false"><span>12</span> Extensions to <code>Hash</code></a></h2><h3 id="conversions"><a class="anchorlink" href="#conversions" data-turbo="false"><span>12.1</span> Conversions</a></h3><h4 id="conversions-to-xml"><a class="anchorlink" href="#conversions-to-xml" data-turbo="false"><span>12.1.1</span> <code>to_xml</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-to_xml"><code>to_xml</code></a> returns a string containing an XML representation of its receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">foo: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">bar: </span><span class="mi">2</span> <span class="p">}.</span><span class="nf">to_xml</span> <span class="c1"># =></span> <span class="c1"># <?xml version="1.0" encoding="UTF-8"?></span> <span class="c1"># <hash></span> <span class="c1"># <foo type="integer">1</foo></span> <span class="c1"># <bar type="integer">2</bar></span> <span class="c1"># </hash></span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ foo: 1, bar: 2 }.to_xml # => # <?xml version="1.0" encoding="UTF-8"?> # <hash> # <foo type="integer">1</foo> # <bar type="integer">2</bar> # </hash> ">Copy</button> </div> <p>To do so, the method loops over the pairs and builds nodes that depend on the <em>values</em>. Given a pair <code>key</code>, <code>value</code>:</p> <ul> <li><p>If <code>value</code> is a hash there's a recursive call with <code>key</code> as <code>:root</code>.</p></li> <li><p>If <code>value</code> is an array there's a recursive call with <code>key</code> as <code>:root</code>, and <code>key</code> singularized as <code>:children</code>.</p></li> <li><p>If <code>value</code> is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the <code>options</code> hash as first argument with <code>key</code> as <code>:root</code>, and <code>key</code> singularized as second argument. Its return value becomes a new node.</p></li> <li><p>If <code>value</code> responds to <code>to_xml</code> the method is invoked with <code>key</code> as <code>:root</code>.</p></li> <li><p>Otherwise, a node with <code>key</code> as tag is created with a string representation of <code>value</code> as text node. If <code>value</code> is <code>nil</code> an attribute "nil" set to "true" is added. Unless the option <code>:skip_types</code> exists and is true, an attribute "type" is added as well according to the following mapping:</p></li> </ul> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">XML_TYPE_NAMES</span> <span class="o">=</span> <span class="p">{</span> <span class="s2">"Symbol"</span> <span class="o">=></span> <span class="s2">"symbol"</span><span class="p">,</span> <span class="s2">"Integer"</span> <span class="o">=></span> <span class="s2">"integer"</span><span class="p">,</span> <span class="s2">"BigDecimal"</span> <span class="o">=></span> <span class="s2">"decimal"</span><span class="p">,</span> <span class="s2">"Float"</span> <span class="o">=></span> <span class="s2">"float"</span><span class="p">,</span> <span class="s2">"TrueClass"</span> <span class="o">=></span> <span class="s2">"boolean"</span><span class="p">,</span> <span class="s2">"FalseClass"</span> <span class="o">=></span> <span class="s2">"boolean"</span><span class="p">,</span> <span class="s2">"Date"</span> <span class="o">=></span> <span class="s2">"date"</span><span class="p">,</span> <span class="s2">"DateTime"</span> <span class="o">=></span> <span class="s2">"datetime"</span><span class="p">,</span> <span class="s2">"Time"</span> <span class="o">=></span> <span class="s2">"datetime"</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="XML_TYPE_NAMES = { "Symbol" => "symbol", "Integer" => "integer", "BigDecimal" => "decimal", "Float" => "float", "TrueClass" => "boolean", "FalseClass" => "boolean", "Date" => "date", "DateTime" => "datetime", "Time" => "datetime" } ">Copy</button> </div> <p>By default the root node is "hash", but that's configurable via the <code>:root</code> option.</p><p>The default XML builder is a fresh instance of <code>Builder::XmlMarkup</code>. You can configure your own builder with the <code>:builder</code> option. The method also accepts options like <code>:dasherize</code> and friends, they are forwarded to the builder.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/conversions.rb">active_support/core_ext/hash/conversions.rb</a></code>.</p></div><h3 id="merging"><a class="anchorlink" href="#merging" data-turbo="false"><span>12.2</span> Merging</a></h3><p>Ruby has a built-in method <code>Hash#merge</code> that merges two hashes:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">b: </span><span class="mi">1</span> <span class="p">}.</span><span class="nf">merge</span><span class="p">(</span><span class="ss">a: </span><span class="mi">0</span><span class="p">,</span> <span class="ss">c: </span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => {:a=>0, :b=>1, :c=>2}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ a: 1, b: 1 }.merge(a: 0, c: 2) # => {:a=>0, :b=>1, :c=>2} ">Copy</button> </div> <p>Active Support defines a few more ways of merging hashes that may be convenient.</p><h4 id="reverse-merge-and-reverse-merge-bang"><a class="anchorlink" href="#reverse-merge-and-reverse-merge-bang" data-turbo="false"><span>12.2.1</span> <code>reverse_merge</code> and <code>reverse_merge!</code></a></h4><p>In case of collision the key in the hash of the argument wins in <code>merge</code>. You can support option hashes with default values in a compact way with this idiom:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">options</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">length: </span><span class="mi">30</span><span class="p">,</span> <span class="ss">omission: </span><span class="s2">"..."</span> <span class="p">}.</span><span class="nf">merge</span><span class="p">(</span><span class="n">options</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="options = { length: 30, omission: "..." }.merge(options) ">Copy</button> </div> <p>Active Support defines <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-reverse_merge"><code>reverse_merge</code></a> in case you prefer this alternative notation:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">options</span> <span class="o">=</span> <span class="n">options</span><span class="p">.</span><span class="nf">reverse_merge</span><span class="p">(</span><span class="ss">length: </span><span class="mi">30</span><span class="p">,</span> <span class="ss">omission: </span><span class="s2">"..."</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="options = options.reverse_merge(length: 30, omission: "...") ">Copy</button> </div> <p>And a bang version <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-reverse_merge-21"><code>reverse_merge!</code></a> that performs the merge in place:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">options</span><span class="p">.</span><span class="nf">reverse_merge!</span><span class="p">(</span><span class="ss">length: </span><span class="mi">30</span><span class="p">,</span> <span class="ss">omission: </span><span class="s2">"..."</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="options.reverse_merge!(length: 30, omission: "...") ">Copy</button> </div> <div class="interstitial warning"><p>Take into account that <code>reverse_merge!</code> may change the hash in the caller, which may or may not be a good idea.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb">active_support/core_ext/hash/reverse_merge.rb</a></code>.</p></div><h4 id="reverse-update"><a class="anchorlink" href="#reverse-update" data-turbo="false"><span>12.2.2</span> <code>reverse_update</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-reverse_update"><code>reverse_update</code></a> is an alias for <code>reverse_merge!</code>, explained above.</p><div class="interstitial warning"><p>Note that <code>reverse_update</code> has no bang.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb">active_support/core_ext/hash/reverse_merge.rb</a></code>.</p></div><h4 id="deep-merge-and-deep-merge-bang"><a class="anchorlink" href="#deep-merge-and-deep-merge-bang" data-turbo="false"><span>12.2.3</span> <code>deep_merge</code> and <code>deep_merge!</code></a></h4><p>As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins.</p><p>Active Support defines <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-deep_merge"><code>Hash#deep_merge</code></a>. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their <em>merge</em> becomes the value in the resulting hash:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">a: </span><span class="p">{</span> <span class="ss">b: </span><span class="mi">1</span> <span class="p">}</span> <span class="p">}.</span><span class="nf">deep_merge</span><span class="p">(</span><span class="ss">a: </span><span class="p">{</span> <span class="ss">c: </span><span class="mi">2</span> <span class="p">})</span> <span class="c1"># => {:a=>{:b=>1, :c=>2}}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ a: { b: 1 } }.deep_merge(a: { c: 2 }) # => {:a=>{:b=>1, :c=>2}} ">Copy</button> </div> <p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-deep_merge-21"><code>deep_merge!</code></a> performs a deep merge in place.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/deep_merge.rb">active_support/core_ext/hash/deep_merge.rb</a></code>.</p></div><h3 id="deep-duplicating"><a class="anchorlink" href="#deep-duplicating" data-turbo="false"><span>12.3</span> Deep Duplicating</a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-deep_dup"><code>Hash#deep_dup</code></a> duplicates itself and all keys and values inside recursively with Active Support method <code>Object#deep_dup</code>. It works like <code>Enumerator#each_with_object</code> with sending <code>deep_dup</code> method to each pair inside.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">hash</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">b: </span><span class="p">{</span> <span class="ss">c: </span><span class="mi">2</span><span class="p">,</span> <span class="ss">d: </span><span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">]</span> <span class="p">}</span> <span class="p">}</span> <span class="nb">dup</span> <span class="o">=</span> <span class="nb">hash</span><span class="p">.</span><span class="nf">deep_dup</span> <span class="nb">dup</span><span class="p">[</span><span class="ss">:b</span><span class="p">][</span><span class="ss">:e</span><span class="p">]</span> <span class="o">=</span> <span class="mi">5</span> <span class="nb">dup</span><span class="p">[</span><span class="ss">:b</span><span class="p">][</span><span class="ss">:d</span><span class="p">]</span> <span class="o"><<</span> <span class="mi">5</span> <span class="nb">hash</span><span class="p">[</span><span class="ss">:b</span><span class="p">][</span><span class="ss">:e</span><span class="p">]</span> <span class="o">==</span> <span class="kp">nil</span> <span class="c1"># => true</span> <span class="nb">hash</span><span class="p">[</span><span class="ss">:b</span><span class="p">][</span><span class="ss">:d</span><span class="p">]</span> <span class="o">==</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">]</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="hash = { a: 1, b: { c: 2, d: [3, 4] } } dup = hash.deep_dup dup[:b][:e] = 5 dup[:b][:d] << 5 hash[:b][:e] == nil # => true hash[:b][:d] == [3, 4] # => true ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/object/deep_dup.rb">active_support/core_ext/object/deep_dup.rb</a></code>.</p></div><h3 id="working-with-keys"><a class="anchorlink" href="#working-with-keys" data-turbo="false"><span>12.4</span> Working with Keys</a></h3><h4 id="except-bang"><a class="anchorlink" href="#except-bang" data-turbo="false"><span>12.4.1</span> <code>except!</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-except-21"><code>except!</code></a> is identical to the built-in <code>except</code> method but removes keys in place, returning <code>self</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">b: </span><span class="mi">2</span> <span class="p">}.</span><span class="nf">except!</span><span class="p">(</span><span class="ss">:a</span><span class="p">)</span> <span class="c1"># => {:b=>2}</span> <span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">b: </span><span class="mi">2</span> <span class="p">}.</span><span class="nf">except!</span><span class="p">(</span><span class="ss">:c</span><span class="p">)</span> <span class="c1"># => {:a=>1, :b=>2}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ a: 1, b: 2 }.except!(:a) # => {:b=>2} { a: 1, b: 2 }.except!(:c) # => {:a=>1, :b=>2} ">Copy</button> </div> <p>If the receiver responds to <code>convert_key</code>, the method is called on each of the arguments. This allows <code>except!</code> (and <code>except</code>) to play nice with hashes with indifferent access for instance:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span> <span class="p">}.</span><span class="nf">with_indifferent_access</span><span class="p">.</span><span class="nf">except!</span><span class="p">(</span><span class="ss">:a</span><span class="p">)</span> <span class="c1"># => {}</span> <span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span> <span class="p">}.</span><span class="nf">with_indifferent_access</span><span class="p">.</span><span class="nf">except!</span><span class="p">(</span><span class="s2">"a"</span><span class="p">)</span> <span class="c1"># => {}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ a: 1 }.with_indifferent_access.except!(:a) # => {} { a: 1 }.with_indifferent_access.except!("a") # => {} ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/except.rb">active_support/core_ext/hash/except.rb</a></code>.</p></div><h4 id="stringify-keys-and-stringify-keys-bang"><a class="anchorlink" href="#stringify-keys-and-stringify-keys-bang" data-turbo="false"><span>12.4.2</span> <code>stringify_keys</code> and <code>stringify_keys!</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-stringify_keys"><code>stringify_keys</code></a> returns a hash that has a stringified version of the keys in the receiver. It does so by sending <code>to_s</code> to them:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="kp">nil</span> <span class="o">=></span> <span class="kp">nil</span><span class="p">,</span> <span class="mi">1</span> <span class="o">=></span> <span class="mi">1</span><span class="p">,</span> <span class="ss">a: :a</span> <span class="p">}.</span><span class="nf">stringify_keys</span> <span class="c1"># => {"" => nil, "1" => 1, "a" => :a}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ nil => nil, 1 => 1, a: :a }.stringify_keys # => {"" => nil, "1" => 1, "a" => :a} ">Copy</button> </div> <p>In case of key collision, the value will be the one most recently inserted into the hash:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="s2">"a"</span> <span class="o">=></span> <span class="mi">1</span><span class="p">,</span> <span class="ss">a: </span><span class="mi">2</span> <span class="p">}.</span><span class="nf">stringify_keys</span> <span class="c1"># The result will be</span> <span class="c1"># => {"a"=>2}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ "a" => 1, a: 2 }.stringify_keys # The result will be # => {"a"=>2} ">Copy</button> </div> <p>This method may be useful for example to easily accept both symbols and strings as options. For instance <code>ActionView::Helpers::FormHelper</code> defines:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">to_checkbox_tag</span><span class="p">(</span><span class="n">options</span> <span class="o">=</span> <span class="p">{},</span> <span class="n">checked_value</span> <span class="o">=</span> <span class="s2">"1"</span><span class="p">,</span> <span class="n">unchecked_value</span> <span class="o">=</span> <span class="s2">"0"</span><span class="p">)</span> <span class="n">options</span> <span class="o">=</span> <span class="n">options</span><span class="p">.</span><span class="nf">stringify_keys</span> <span class="n">options</span><span class="p">[</span><span class="s2">"type"</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"checkbox"</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def to_checkbox_tag(options = {}, checked_value = "1", unchecked_value = "0") options = options.stringify_keys options["type"] = "checkbox" # ... end ">Copy</button> </div> <p>The second line can safely access the "type" key, and let the user to pass either <code>:type</code> or "type".</p><p>There's also the bang variant <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-stringify_keys-21"><code>stringify_keys!</code></a> that stringifies keys in place.</p><p>Besides that, one can use <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-deep_stringify_keys"><code>deep_stringify_keys</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-deep_stringify_keys-21"><code>deep_stringify_keys!</code></a> to stringify all the keys in the given hash and all the hashes nested in it. An example of the result is:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="kp">nil</span> <span class="o">=></span> <span class="kp">nil</span><span class="p">,</span> <span class="mi">1</span> <span class="o">=></span> <span class="mi">1</span><span class="p">,</span> <span class="ss">nested: </span><span class="p">{</span> <span class="ss">a: </span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span> <span class="o">=></span> <span class="mi">5</span> <span class="p">}</span> <span class="p">}.</span><span class="nf">deep_stringify_keys</span> <span class="c1"># => {""=>nil, "1"=>1, "nested"=>{"a"=>3, "5"=>5}}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ nil => nil, 1 => 1, nested: { a: 3, 5 => 5 } }.deep_stringify_keys # => {""=>nil, "1"=>1, "nested"=>{"a"=>3, "5"=>5}} ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/keys.rb">active_support/core_ext/hash/keys.rb</a></code>.</p></div><h4 id="symbolize-keys-and-symbolize-keys-bang"><a class="anchorlink" href="#symbolize-keys-and-symbolize-keys-bang" data-turbo="false"><span>12.4.3</span> <code>symbolize_keys</code> and <code>symbolize_keys!</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-symbolize_keys"><code>symbolize_keys</code></a> returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending <code>to_sym</code> to them:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="kp">nil</span> <span class="o">=></span> <span class="kp">nil</span><span class="p">,</span> <span class="mi">1</span> <span class="o">=></span> <span class="mi">1</span><span class="p">,</span> <span class="s2">"a"</span> <span class="o">=></span> <span class="s2">"a"</span> <span class="p">}.</span><span class="nf">symbolize_keys</span> <span class="c1"># => {nil=>nil, 1=>1, :a=>"a"}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ nil => nil, 1 => 1, "a" => "a" }.symbolize_keys # => {nil=>nil, 1=>1, :a=>"a"} ">Copy</button> </div> <div class="interstitial warning"><p>Note in the previous example only one key was symbolized.</p></div><p>In case of key collision, the value will be the one most recently inserted into the hash:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="s2">"a"</span> <span class="o">=></span> <span class="mi">1</span><span class="p">,</span> <span class="ss">a: </span><span class="mi">2</span> <span class="p">}.</span><span class="nf">symbolize_keys</span> <span class="c1"># => {:a=>2}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ "a" => 1, a: 2 }.symbolize_keys # => {:a=>2} ">Copy</button> </div> <p>This method may be useful for example to easily accept both symbols and strings as options. For instance <code>ActionText::TagHelper</code> defines</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">rich_textarea_tag</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">value</span> <span class="o">=</span> <span class="kp">nil</span><span class="p">,</span> <span class="n">options</span> <span class="o">=</span> <span class="p">{})</span> <span class="n">options</span> <span class="o">=</span> <span class="n">options</span><span class="p">.</span><span class="nf">symbolize_keys</span> <span class="n">options</span><span class="p">[</span><span class="ss">:input</span><span class="p">]</span> <span class="o">||=</span> <span class="s2">"trix_input_</span><span class="si">#{</span><span class="no">ActionText</span><span class="o">::</span><span class="no">TagHelper</span><span class="p">.</span><span class="nf">id</span> <span class="o">+=</span> <span class="mi">1</span><span class="si">}</span><span class="s2">"</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def rich_textarea_tag(name, value = nil, options = {}) options = options.symbolize_keys options[:input] ||= "trix_input_#{ActionText::TagHelper.id += 1}" # ... end ">Copy</button> </div> <p>The third line can safely access the <code>:input</code> key, and let the user to pass either <code>:input</code> or "input".</p><p>There's also the bang variant <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-symbolize_keys-21"><code>symbolize_keys!</code></a> that symbolizes keys in place.</p><p>Besides that, one can use <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-deep_symbolize_keys"><code>deep_symbolize_keys</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-deep_symbolize_keys-21"><code>deep_symbolize_keys!</code></a> to symbolize all the keys in the given hash and all the hashes nested in it. An example of the result is:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="kp">nil</span> <span class="o">=></span> <span class="kp">nil</span><span class="p">,</span> <span class="mi">1</span> <span class="o">=></span> <span class="mi">1</span><span class="p">,</span> <span class="s2">"nested"</span> <span class="o">=></span> <span class="p">{</span> <span class="s2">"a"</span> <span class="o">=></span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span> <span class="o">=></span> <span class="mi">5</span> <span class="p">}</span> <span class="p">}.</span><span class="nf">deep_symbolize_keys</span> <span class="c1"># => {nil=>nil, 1=>1, nested:{a:3, 5=>5}}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ nil => nil, 1 => 1, "nested" => { "a" => 3, 5 => 5 } }.deep_symbolize_keys # => {nil=>nil, 1=>1, nested:{a:3, 5=>5}} ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/keys.rb">active_support/core_ext/hash/keys.rb</a></code>.</p></div><h4 id="to-options-and-to-options-bang"><a class="anchorlink" href="#to-options-and-to-options-bang" data-turbo="false"><span>12.4.4</span> <code>to_options</code> and <code>to_options!</code></a></h4><p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-to_options"><code>to_options</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-to_options-21"><code>to_options!</code></a> are aliases of <code>symbolize_keys</code> and <code>symbolize_keys!</code>, respectively.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/keys.rb">active_support/core_ext/hash/keys.rb</a></code>.</p></div><h4 id="assert-valid-keys"><a class="anchorlink" href="#assert-valid-keys" data-turbo="false"><span>12.4.5</span> <code>assert_valid_keys</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-assert_valid_keys"><code>assert_valid_keys</code></a> receives an arbitrary number of arguments, and checks whether the receiver has any key outside that list. If it does <code>ArgumentError</code> is raised.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span> <span class="p">}.</span><span class="nf">assert_valid_keys</span><span class="p">(</span><span class="ss">:a</span><span class="p">)</span> <span class="c1"># passes</span> <span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span> <span class="p">}.</span><span class="nf">assert_valid_keys</span><span class="p">(</span><span class="s2">"a"</span><span class="p">)</span> <span class="c1"># ArgumentError</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ a: 1 }.assert_valid_keys(:a) # passes { a: 1 }.assert_valid_keys("a") # ArgumentError ">Copy</button> </div> <p>Active Record does not accept unknown options when building associations, for example. It implements that control via <code>assert_valid_keys</code>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/keys.rb">active_support/core_ext/hash/keys.rb</a></code>.</p></div><h3 id="working-with-values"><a class="anchorlink" href="#working-with-values" data-turbo="false"><span>12.5</span> Working with Values</a></h3><h4 id="deep-transform-values-and-deep-transform-values-bang"><a class="anchorlink" href="#deep-transform-values-and-deep-transform-values-bang" data-turbo="false"><span>12.5.1</span> <code>deep_transform_values</code> and <code>deep_transform_values!</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-deep_transform_values"><code>deep_transform_values</code></a> returns a new hash with all values converted by the block operation. This includes the values from the root hash and from all nested hashes and arrays.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">hash</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">person: </span><span class="p">{</span> <span class="ss">name: </span><span class="s2">"Rob"</span><span class="p">,</span> <span class="ss">age: </span><span class="s2">"28"</span> <span class="p">}</span> <span class="p">}</span> <span class="nb">hash</span><span class="p">.</span><span class="nf">deep_transform_values</span> <span class="p">{</span> <span class="o">|</span><span class="n">value</span><span class="o">|</span> <span class="n">value</span><span class="p">.</span><span class="nf">to_s</span><span class="p">.</span><span class="nf">upcase</span> <span class="p">}</span> <span class="c1"># => {person: {name: "ROB", age: "28"}}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="hash = { person: { name: "Rob", age: "28" } } hash.deep_transform_values { |value| value.to_s.upcase } # => {person: {name: "ROB", age: "28"}} ">Copy</button> </div> <p>There's also the bang variant <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-deep_transform_values-21"><code>deep_transform_values!</code></a> that destructively converts all values by using the block operation.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/deep_transform_values.rb">active_support/core_ext/hash/deep_transform_values.rb</a></code>.</p></div><h3 id="slicing"><a class="anchorlink" href="#slicing" data-turbo="false"><span>12.6</span> Slicing</a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-slice-21"><code>slice!</code></a> replaces the hash with only the given keys and returns a hash containing the removed key/value pairs.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">hash</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">b: </span><span class="mi">2</span> <span class="p">}</span> <span class="n">rest</span> <span class="o">=</span> <span class="nb">hash</span><span class="p">.</span><span class="nf">slice!</span><span class="p">(</span><span class="ss">:a</span><span class="p">)</span> <span class="c1"># => {:b=>2}</span> <span class="nb">hash</span> <span class="c1"># => {:a=>1}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="hash = { a: 1, b: 2 } rest = hash.slice!(:a) # => {:b=>2} hash # => {:a=>1} ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/slice.rb">active_support/core_ext/hash/slice.rb</a></code>.</p></div><h3 id="extensions-to-hash-extracting"><a class="anchorlink" href="#extensions-to-hash-extracting" data-turbo="false"><span>12.7</span> Extracting</a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-extract-21"><code>extract!</code></a> removes and returns the key/value pairs matching the given keys.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">hash</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">b: </span><span class="mi">2</span> <span class="p">}</span> <span class="n">rest</span> <span class="o">=</span> <span class="nb">hash</span><span class="p">.</span><span class="nf">extract!</span><span class="p">(</span><span class="ss">:a</span><span class="p">)</span> <span class="c1"># => {:a=>1}</span> <span class="nb">hash</span> <span class="c1"># => {:b=>2}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="hash = { a: 1, b: 2 } rest = hash.extract!(:a) # => {:a=>1} hash # => {:b=>2} ">Copy</button> </div> <p>The method <code>extract!</code> returns the same subclass of Hash that the receiver is.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">hash</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">b: </span><span class="mi">2</span> <span class="p">}.</span><span class="nf">with_indifferent_access</span> <span class="n">rest</span> <span class="o">=</span> <span class="nb">hash</span><span class="p">.</span><span class="nf">extract!</span><span class="p">(</span><span class="ss">:a</span><span class="p">).</span><span class="nf">class</span> <span class="c1"># => ActiveSupport::HashWithIndifferentAccess</span> </code></pre> <button class="clipboard-button" data-clipboard-text="hash = { a: 1, b: 2 }.with_indifferent_access rest = hash.extract!(:a).class # => ActiveSupport::HashWithIndifferentAccess ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/slice.rb">active_support/core_ext/hash/slice.rb</a></code>.</p></div><h3 id="indifferent-access"><a class="anchorlink" href="#indifferent-access" data-turbo="false"><span>12.8</span> Indifferent Access</a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Hash.html#method-i-with_indifferent_access"><code>with_indifferent_access</code></a> returns an <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/HashWithIndifferentAccess.html"><code>ActiveSupport::HashWithIndifferentAccess</code></a> out of its receiver:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">a: </span><span class="mi">1</span> <span class="p">}.</span><span class="nf">with_indifferent_access</span><span class="p">[</span><span class="s2">"a"</span><span class="p">]</span> <span class="c1"># => 1</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ a: 1 }.with_indifferent_access["a"] # => 1 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb">active_support/core_ext/hash/indifferent_access.rb</a></code>.</p></div><h2 id="extensions-to-regexp"><a class="anchorlink" href="#extensions-to-regexp" data-turbo="false"><span>13</span> Extensions to <code>Regexp</code></a></h2><h3 id="multiline-questionmark"><a class="anchorlink" href="#multiline-questionmark" data-turbo="false"><span>13.1</span> <code>multiline?</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Regexp.html#method-i-multiline-3F"><code>multiline?</code></a> says whether a regexp has the <code>/m</code> flag set, that is, whether the dot matches newlines.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="sr">%r{.}</span><span class="p">.</span><span class="nf">multiline?</span> <span class="c1"># => false</span> <span class="sr">%r{.}m</span><span class="p">.</span><span class="nf">multiline?</span> <span class="c1"># => true</span> <span class="no">Regexp</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"."</span><span class="p">).</span><span class="nf">multiline?</span> <span class="c1"># => false</span> <span class="no">Regexp</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"."</span><span class="p">,</span> <span class="no">Regexp</span><span class="o">::</span><span class="no">MULTILINE</span><span class="p">).</span><span class="nf">multiline?</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="%r{.}.multiline? # => false %r{.}m.multiline? # => true Regexp.new(".").multiline? # => false Regexp.new(".", Regexp::MULTILINE).multiline? # => true ">Copy</button> </div> <p>Rails uses this method in a single place, also in the routing code. Multiline regexps are disallowed for route requirements and this flag eases enforcing that constraint.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">verify_regexp_requirements</span><span class="p">(</span><span class="n">requirements</span><span class="p">)</span> <span class="c1"># ...</span> <span class="k">if</span> <span class="n">requirement</span><span class="p">.</span><span class="nf">multiline?</span> <span class="k">raise</span> <span class="no">ArgumentError</span><span class="p">,</span> <span class="s2">"Regexp multiline option is not allowed in routing requirements: </span><span class="si">#{</span><span class="n">requirement</span><span class="p">.</span><span class="nf">inspect</span><span class="si">}</span><span class="s2">"</span> <span class="k">end</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def verify_regexp_requirements(requirements) # ... if requirement.multiline? raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}" end # ... end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/regexp.rb">active_support/core_ext/regexp.rb</a></code>.</p></div><h2 id="extensions-to-range"><a class="anchorlink" href="#extensions-to-range" data-turbo="false"><span>14</span> Extensions to <code>Range</code></a></h2><h3 id="extensions-to-range-to-fs"><a class="anchorlink" href="#extensions-to-range-to-fs" data-turbo="false"><span>14.1</span> <code>to_fs</code></a></h3><p>Active Support defines <code>Range#to_fs</code> as an alternative to <code>to_s</code> that understands an optional format argument. As of this writing the only supported non-default format is <code>:db</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">(</span><span class="no">Date</span><span class="p">.</span><span class="nf">today</span><span class="o">..</span><span class="no">Date</span><span class="p">.</span><span class="nf">tomorrow</span><span class="p">).</span><span class="nf">to_fs</span> <span class="c1"># => "2009-10-25..2009-10-26"</span> <span class="p">(</span><span class="no">Date</span><span class="p">.</span><span class="nf">today</span><span class="o">..</span><span class="no">Date</span><span class="p">.</span><span class="nf">tomorrow</span><span class="p">).</span><span class="nf">to_fs</span><span class="p">(</span><span class="ss">:db</span><span class="p">)</span> <span class="c1"># => "BETWEEN '2009-10-25' AND '2009-10-26'"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="(Date.today..Date.tomorrow).to_fs # => "2009-10-25..2009-10-26" (Date.today..Date.tomorrow).to_fs(:db) # => "BETWEEN '2009-10-25' AND '2009-10-26'" ">Copy</button> </div> <p>As the example depicts, the <code>:db</code> format generates a <code>BETWEEN</code> SQL clause. That is used by Active Record in its support for range values in conditions.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/range/conversions.rb">active_support/core_ext/range/conversions.rb</a></code>.</p></div><h3 id="and-include-questionmark"><a class="anchorlink" href="#and-include-questionmark" data-turbo="false"><span>14.2</span> <code>===</code> and <code>include?</code></a></h3><p>The methods <code>Range#===</code> and <code>Range#include?</code> say whether some value falls between the ends of a given instance:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">(</span><span class="mi">2</span><span class="o">..</span><span class="mi">3</span><span class="p">).</span><span class="nf">include?</span><span class="p">(</span><span class="no">Math</span><span class="o">::</span><span class="no">E</span><span class="p">)</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="(2..3).include?(Math::E) # => true ">Copy</button> </div> <p>Active Support extends these methods so that the argument may be another range in turn. In that case we test whether the ends of the argument range belong to the receiver themselves:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">10</span><span class="p">)</span> <span class="o">===</span> <span class="p">(</span><span class="mi">3</span><span class="o">..</span><span class="mi">7</span><span class="p">)</span> <span class="c1"># => true</span> <span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">10</span><span class="p">)</span> <span class="o">===</span> <span class="p">(</span><span class="mi">0</span><span class="o">..</span><span class="mi">7</span><span class="p">)</span> <span class="c1"># => false</span> <span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">10</span><span class="p">)</span> <span class="o">===</span> <span class="p">(</span><span class="mi">3</span><span class="o">..</span><span class="mi">11</span><span class="p">)</span> <span class="c1"># => false</span> <span class="p">(</span><span class="mi">1</span><span class="o">...</span><span class="mi">9</span><span class="p">)</span> <span class="o">===</span> <span class="p">(</span><span class="mi">3</span><span class="o">..</span><span class="mi">9</span><span class="p">)</span> <span class="c1"># => false</span> <span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">10</span><span class="p">).</span><span class="nf">include?</span><span class="p">(</span><span class="mi">3</span><span class="o">..</span><span class="mi">7</span><span class="p">)</span> <span class="c1"># => true</span> <span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">10</span><span class="p">).</span><span class="nf">include?</span><span class="p">(</span><span class="mi">0</span><span class="o">..</span><span class="mi">7</span><span class="p">)</span> <span class="c1"># => false</span> <span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">10</span><span class="p">).</span><span class="nf">include?</span><span class="p">(</span><span class="mi">3</span><span class="o">..</span><span class="mi">11</span><span class="p">)</span> <span class="c1"># => false</span> <span class="p">(</span><span class="mi">1</span><span class="o">...</span><span class="mi">9</span><span class="p">).</span><span class="nf">include?</span><span class="p">(</span><span class="mi">3</span><span class="o">..</span><span class="mi">9</span><span class="p">)</span> <span class="c1"># => false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="(1..10) === (3..7) # => true (1..10) === (0..7) # => false (1..10) === (3..11) # => false (1...9) === (3..9) # => false (1..10).include?(3..7) # => true (1..10).include?(0..7) # => false (1..10).include?(3..11) # => false (1...9).include?(3..9) # => false ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/range/compare_range.rb">active_support/core_ext/range/compare_range.rb</a></code>.</p></div><h3 id="overlap-questionmark"><a class="anchorlink" href="#overlap-questionmark" data-turbo="false"><span>14.3</span> <code>overlap?</code></a></h3><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Range.html#method-i-overlaps-3F"><code>Range#overlap?</code></a> says whether any two given ranges have non-void intersection:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">10</span><span class="p">).</span><span class="nf">overlap?</span><span class="p">(</span><span class="mi">7</span><span class="o">..</span><span class="mi">11</span><span class="p">)</span> <span class="c1"># => true</span> <span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">10</span><span class="p">).</span><span class="nf">overlap?</span><span class="p">(</span><span class="mi">0</span><span class="o">..</span><span class="mi">7</span><span class="p">)</span> <span class="c1"># => true</span> <span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">10</span><span class="p">).</span><span class="nf">overlap?</span><span class="p">(</span><span class="mi">11</span><span class="o">..</span><span class="mi">27</span><span class="p">)</span> <span class="c1"># => false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="(1..10).overlap?(7..11) # => true (1..10).overlap?(0..7) # => true (1..10).overlap?(11..27) # => false ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/range/overlap.rb">active_support/core_ext/range/overlap.rb</a></code>.</p></div><h2 id="extensions-to-date"><a class="anchorlink" href="#extensions-to-date" data-turbo="false"><span>15</span> Extensions to <code>Date</code></a></h2><h3 id="extensions-to-date-calculations"><a class="anchorlink" href="#extensions-to-date-calculations" data-turbo="false"><span>15.1</span> Calculations</a></h3><div class="interstitial info"><p>The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, <code>Date.new(1582, 10, 4).tomorrow</code> returns <code>Date.new(1582, 10, 15)</code> and so on. Please check <code>test/core_ext/date_ext_test.rb</code> in the Active Support test suite for expected behavior.</p></div><h4 id="date-current"><a class="anchorlink" href="#date-current" data-turbo="false"><span>15.1.1</span> <code>Date.current</code></a></h4><p>Active Support defines <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-c-current"><code>Date.current</code></a> to be today in the current time zone. That's like <code>Date.today</code>, except that it honors the user time zone, if defined. It also defines <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-c-yesterday"><code>Date.yesterday</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-c-tomorrow"><code>Date.tomorrow</code></a>, and the instance predicates <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-past-3F"><code>past?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-today-3F"><code>today?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-tomorrow-3F"><code>tomorrow?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-next_day-3F"><code>next_day?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-yesterday-3F"><code>yesterday?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-prev_day-3F"><code>prev_day?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-future-3F"><code>future?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-on_weekday-3F"><code>on_weekday?</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-on_weekend-3F"><code>on_weekend?</code></a>, all of them relative to <code>Date.current</code>.</p><p>When making Date comparisons using methods which honor the user time zone, make sure to use <code>Date.current</code> and not <code>Date.today</code>. There are cases where the user time zone might be in the future compared to the system time zone, which <code>Date.today</code> uses by default. This means <code>Date.today</code> may equal <code>Date.yesterday</code>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date/calculations.rb">active_support/core_ext/date/calculations.rb</a></code>.</p></div><h4 id="named-dates"><a class="anchorlink" href="#named-dates" data-turbo="false"><span>15.1.2</span> Named Dates</a></h4><h5 id="beginning-of-week-end-of-week"><a class="anchorlink" href="#beginning-of-week-end-of-week" data-turbo="false"><span>15.1.2.1</span> <code>beginning_of_week</code>, <code>end_of_week</code></a></h5><p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-beginning_of_week"><code>beginning_of_week</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-end_of_week"><code>end_of_week</code></a> return the dates for the beginning and end of the week, respectively. Weeks are assumed to start on Monday, but that can be changed passing an argument, setting thread local <code>Date.beginning_of_week</code> or <a href="configuring.html#config-beginning-of-week"><code>config.beginning_of_week</code></a>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="c1"># => Sat, 08 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">beginning_of_week</span> <span class="c1"># => Mon, 03 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">beginning_of_week</span><span class="p">(</span><span class="ss">:sunday</span><span class="p">)</span> <span class="c1"># => Sun, 02 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">end_of_week</span> <span class="c1"># => Sun, 09 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">end_of_week</span><span class="p">(</span><span class="ss">:sunday</span><span class="p">)</span> <span class="c1"># => Sat, 08 May 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = Date.new(2010, 5, 8) # => Sat, 08 May 2010 d.beginning_of_week # => Mon, 03 May 2010 d.beginning_of_week(:sunday) # => Sun, 02 May 2010 d.end_of_week # => Sun, 09 May 2010 d.end_of_week(:sunday) # => Sat, 08 May 2010 ">Copy</button> </div> <p><code>beginning_of_week</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_week"><code>at_beginning_of_week</code></a> and <code>end_of_week</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-at_end_of_week"><code>at_end_of_week</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h5 id="monday-sunday"><a class="anchorlink" href="#monday-sunday" data-turbo="false"><span>15.1.2.2</span> <code>monday</code>, <code>sunday</code></a></h5><p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-monday"><code>monday</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-sunday"><code>sunday</code></a> return the dates for the previous Monday and next Sunday, respectively.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="c1"># => Sat, 08 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">monday</span> <span class="c1"># => Mon, 03 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">sunday</span> <span class="c1"># => Sun, 09 May 2010</span> <span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span> <span class="c1"># => Mon, 10 Sep 2012</span> <span class="n">d</span><span class="p">.</span><span class="nf">monday</span> <span class="c1"># => Mon, 10 Sep 2012</span> <span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">16</span><span class="p">)</span> <span class="c1"># => Sun, 16 Sep 2012</span> <span class="n">d</span><span class="p">.</span><span class="nf">sunday</span> <span class="c1"># => Sun, 16 Sep 2012</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = Date.new(2010, 5, 8) # => Sat, 08 May 2010 d.monday # => Mon, 03 May 2010 d.sunday # => Sun, 09 May 2010 d = Date.new(2012, 9, 10) # => Mon, 10 Sep 2012 d.monday # => Mon, 10 Sep 2012 d = Date.new(2012, 9, 16) # => Sun, 16 Sep 2012 d.sunday # => Sun, 16 Sep 2012 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h5 id="prev-week-next-week"><a class="anchorlink" href="#prev-week-next-week" data-turbo="false"><span>15.1.2.3</span> <code>prev_week</code>, <code>next_week</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-next_week"><code>next_week</code></a> receives a symbol with a day name in English (default is the thread local <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-c-beginning_of_week"><code>Date.beginning_of_week</code></a>, or <a href="configuring.html#config-beginning-of-week"><code>config.beginning_of_week</code></a>, or <code>:monday</code>) and it returns the date corresponding to that day.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span> <span class="c1"># => Sun, 09 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">next_week</span> <span class="c1"># => Mon, 10 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">next_week</span><span class="p">(</span><span class="ss">:saturday</span><span class="p">)</span> <span class="c1"># => Sat, 15 May 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = Date.new(2010, 5, 9) # => Sun, 09 May 2010 d.next_week # => Mon, 10 May 2010 d.next_week(:saturday) # => Sat, 15 May 2010 ">Copy</button> </div> <p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-prev_week"><code>prev_week</code></a> is analogous:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span><span class="p">.</span><span class="nf">prev_week</span> <span class="c1"># => Mon, 26 Apr 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">prev_week</span><span class="p">(</span><span class="ss">:saturday</span><span class="p">)</span> <span class="c1"># => Sat, 01 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">prev_week</span><span class="p">(</span><span class="ss">:friday</span><span class="p">)</span> <span class="c1"># => Fri, 30 Apr 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d.prev_week # => Mon, 26 Apr 2010 d.prev_week(:saturday) # => Sat, 01 May 2010 d.prev_week(:friday) # => Fri, 30 Apr 2010 ">Copy</button> </div> <p><code>prev_week</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-last_week"><code>last_week</code></a>.</p><p>Both <code>next_week</code> and <code>prev_week</code> work as expected when <code>Date.beginning_of_week</code> or <code>config.beginning_of_week</code> are set.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h5 id="beginning-of-month-end-of-month"><a class="anchorlink" href="#beginning-of-month-end-of-month" data-turbo="false"><span>15.1.2.4</span> <code>beginning_of_month</code>, <code>end_of_month</code></a></h5><p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-beginning_of_month"><code>beginning_of_month</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-end_of_month"><code>end_of_month</code></a> return the dates for the beginning and end of the month:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span> <span class="c1"># => Sun, 09 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">beginning_of_month</span> <span class="c1"># => Sat, 01 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">end_of_month</span> <span class="c1"># => Mon, 31 May 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = Date.new(2010, 5, 9) # => Sun, 09 May 2010 d.beginning_of_month # => Sat, 01 May 2010 d.end_of_month # => Mon, 31 May 2010 ">Copy</button> </div> <p><code>beginning_of_month</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_month"><code>at_beginning_of_month</code></a>, and <code>end_of_month</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-at_end_of_month"><code>at_end_of_month</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h5 id="quarter-beginning-of-quarter-end-of-quarter"><a class="anchorlink" href="#quarter-beginning-of-quarter-end-of-quarter" data-turbo="false"><span>15.1.2.5</span> <code>quarter</code>, <code>beginning_of_quarter</code>, <code>end_of_quarter</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-quarter"><code>quarter</code></a> returns the quarter of the receiver's calendar year:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span> <span class="c1"># => Sun, 09 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">quarter</span> <span class="c1"># => 2</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = Date.new(2010, 5, 9) # => Sun, 09 May 2010 d.quarter # => 2 ">Copy</button> </div> <p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-beginning_of_quarter"><code>beginning_of_quarter</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-end_of_quarter"><code>end_of_quarter</code></a> return the dates for the beginning and end of the quarter of the receiver's calendar year:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span> <span class="c1"># => Sun, 09 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">beginning_of_quarter</span> <span class="c1"># => Thu, 01 Apr 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">end_of_quarter</span> <span class="c1"># => Wed, 30 Jun 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = Date.new(2010, 5, 9) # => Sun, 09 May 2010 d.beginning_of_quarter # => Thu, 01 Apr 2010 d.end_of_quarter # => Wed, 30 Jun 2010 ">Copy</button> </div> <p><code>beginning_of_quarter</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_quarter"><code>at_beginning_of_quarter</code></a>, and <code>end_of_quarter</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-at_end_of_quarter"><code>at_end_of_quarter</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h5 id="beginning-of-year-end-of-year"><a class="anchorlink" href="#beginning-of-year-end-of-year" data-turbo="false"><span>15.1.2.6</span> <code>beginning_of_year</code>, <code>end_of_year</code></a></h5><p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-beginning_of_year"><code>beginning_of_year</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-end_of_year"><code>end_of_year</code></a> return the dates for the beginning and end of the year:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span> <span class="c1"># => Sun, 09 May 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">beginning_of_year</span> <span class="c1"># => Fri, 01 Jan 2010</span> <span class="n">d</span><span class="p">.</span><span class="nf">end_of_year</span> <span class="c1"># => Fri, 31 Dec 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = Date.new(2010, 5, 9) # => Sun, 09 May 2010 d.beginning_of_year # => Fri, 01 Jan 2010 d.end_of_year # => Fri, 31 Dec 2010 ">Copy</button> </div> <p><code>beginning_of_year</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_year"><code>at_beginning_of_year</code></a>, and <code>end_of_year</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-at_end_of_year"><code>at_end_of_year</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h4 id="other-date-computations"><a class="anchorlink" href="#other-date-computations" data-turbo="false"><span>15.1.3</span> Other Date Computations</a></h4><h5 id="years-ago-years-since"><a class="anchorlink" href="#years-ago-years-since" data-turbo="false"><span>15.1.3.1</span> <code>years_ago</code>, <code>years_since</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-years_ago"><code>years_ago</code></a> receives a number of years and returns the same date those many years ago:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="n">date</span><span class="p">.</span><span class="nf">years_ago</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># => Wed, 07 Jun 2000</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = Date.new(2010, 6, 7) date.years_ago(10) # => Wed, 07 Jun 2000 ">Copy</button> </div> <p><a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-years_since"><code>years_since</code></a> moves forward in time:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="n">date</span><span class="p">.</span><span class="nf">years_since</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># => Sun, 07 Jun 2020</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = Date.new(2010, 6, 7) date.years_since(10) # => Sun, 07 Jun 2020 ">Copy</button> </div> <p>If such a day does not exist, the last day of the corresponding month is returned:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">29</span><span class="p">).</span><span class="nf">years_ago</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="c1"># => Sat, 28 Feb 2009</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">29</span><span class="p">).</span><span class="nf">years_since</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="c1"># => Sat, 28 Feb 2015</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Date.new(2012, 2, 29).years_ago(3) # => Sat, 28 Feb 2009 Date.new(2012, 2, 29).years_since(3) # => Sat, 28 Feb 2015 ">Copy</button> </div> <p><a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-last_year"><code>last_year</code></a> is short-hand for <code>#years_ago(1)</code>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h5 id="months-ago-months-since"><a class="anchorlink" href="#months-ago-months-since" data-turbo="false"><span>15.1.3.2</span> <code>months_ago</code>, <code>months_since</code></a></h5><p>The methods <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-months_ago"><code>months_ago</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-months_since"><code>months_since</code></a> work analogously for months:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">30</span><span class="p">).</span><span class="nf">months_ago</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => Sun, 28 Feb 2010</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">30</span><span class="p">).</span><span class="nf">months_since</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => Wed, 30 Jun 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010 Date.new(2010, 4, 30).months_since(2) # => Wed, 30 Jun 2010 ">Copy</button> </div> <p>If such a day does not exist, the last day of the corresponding month is returned:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">30</span><span class="p">).</span><span class="nf">months_ago</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => Sun, 28 Feb 2010</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2009</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">months_since</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => Sun, 28 Feb 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010 Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010 ">Copy</button> </div> <p><a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-last_month"><code>last_month</code></a> is short-hand for <code>#months_ago(1)</code>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h5 id="weeks-ago-weeks-since"><a class="anchorlink" href="#weeks-ago-weeks-since" data-turbo="false"><span>15.1.3.3</span> <code>weeks_ago</code>, <code>weeks_since</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-weeks_ago"><code>weeks_ago</code></a> and [<code>weeks_since</code>][DateAndTime::Calculations#week_since] work analogously for weeks:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">24</span><span class="p">).</span><span class="nf">weeks_ago</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => Mon, 17 May 2010</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">24</span><span class="p">).</span><span class="nf">weeks_since</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => Mon, 07 Jun 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Date.new(2010, 5, 24).weeks_ago(1) # => Mon, 17 May 2010 Date.new(2010, 5, 24).weeks_since(2) # => Mon, 07 Jun 2010 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h5 id="other-date-computations-advance"><a class="anchorlink" href="#other-date-computations-advance" data-turbo="false"><span>15.1.3.4</span> <code>advance</code></a></h5><p>The most generic way to jump to other days is <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-i-advance"><code>advance</code></a>. This method receives a hash with keys <code>:years</code>, <code>:months</code>, <code>:weeks</code>, <code>:days</code>, and returns a date advanced as much as the present keys indicate:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="n">date</span><span class="p">.</span><span class="nf">advance</span><span class="p">(</span><span class="ss">years: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">weeks: </span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => Mon, 20 Jun 2011</span> <span class="n">date</span><span class="p">.</span><span class="nf">advance</span><span class="p">(</span><span class="ss">months: </span><span class="mi">2</span><span class="p">,</span> <span class="ss">days: </span><span class="o">-</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => Wed, 04 Aug 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = Date.new(2010, 6, 6) date.advance(years: 1, weeks: 2) # => Mon, 20 Jun 2011 date.advance(months: 2, days: -2) # => Wed, 04 Aug 2010 ">Copy</button> </div> <p>Note in the previous example that increments may be negative.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date/calculations.rb">active_support/core_ext/date/calculations.rb</a></code>.</p></div><h4 id="extensions-to-date-calculations-changing-components"><a class="anchorlink" href="#extensions-to-date-calculations-changing-components" data-turbo="false"><span>15.1.4</span> Changing Components</a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-i-change"><code>change</code></a> allows you to get a new date which is the same as the receiver except for the given year, month, or day:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">23</span><span class="p">).</span><span class="nf">change</span><span class="p">(</span><span class="ss">year: </span><span class="mi">2011</span><span class="p">,</span> <span class="ss">month: </span><span class="mi">11</span><span class="p">)</span> <span class="c1"># => Wed, 23 Nov 2011</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Date.new(2010, 12, 23).change(year: 2011, month: 11) # => Wed, 23 Nov 2011 ">Copy</button> </div> <p>This method is not tolerant to non-existing dates, if the change is invalid <code>ArgumentError</code> is raised:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">change</span><span class="p">(</span><span class="ss">month: </span><span class="mi">2</span><span class="p">)</span> <span class="c1"># => ArgumentError: invalid date</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Date.new(2010, 1, 31).change(month: 2) # => ArgumentError: invalid date ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date/calculations.rb">active_support/core_ext/date/calculations.rb</a></code>.</p></div><h4 id="extensions-to-date-calculations-durations"><a class="anchorlink" href="#extensions-to-date-calculations-durations" data-turbo="false"><span>15.1.5</span> Durations</a></h4><p><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Duration.html"><code>Duration</code></a> objects can be added to and subtracted from dates:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Mon, 09 Aug 2010</span> <span class="n">d</span> <span class="o">+</span> <span class="mi">1</span><span class="p">.</span><span class="nf">year</span> <span class="c1"># => Tue, 09 Aug 2011</span> <span class="n">d</span> <span class="o">-</span> <span class="mi">3</span><span class="p">.</span><span class="nf">hours</span> <span class="c1"># => Sun, 08 Aug 2010 21:00:00 UTC +00:00</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = Date.current # => Mon, 09 Aug 2010 d + 1.year # => Tue, 09 Aug 2011 d - 3.hours # => Sun, 08 Aug 2010 21:00:00 UTC +00:00 ">Copy</button> </div> <p>They translate to calls to <code>since</code> or <code>advance</code>. For example here we get the correct jump in the calendar reform:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">1582</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">.</span><span class="nf">day</span> <span class="c1"># => Fri, 15 Oct 1582</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Date.new(1582, 10, 4) + 1.day # => Fri, 15 Oct 1582 ">Copy</button> </div> <h4 id="timestamps"><a class="anchorlink" href="#timestamps" data-turbo="false"><span>15.1.6</span> Timestamps</a></h4><div class="interstitial info"><p>The following methods return a <code>Time</code> object if possible, otherwise a <code>DateTime</code>. If set, they honor the user time zone.</p></div><h5 id="beginning-of-day-end-of-day"><a class="anchorlink" href="#beginning-of-day-end-of-day" data-turbo="false"><span>15.1.6.1</span> <code>beginning_of_day</code>, <code>end_of_day</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-i-beginning_of_day"><code>beginning_of_day</code></a> returns a timestamp at the beginning of the day (00:00:00):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="n">date</span><span class="p">.</span><span class="nf">beginning_of_day</span> <span class="c1"># => Mon Jun 07 00:00:00 +0200 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = Date.new(2010, 6, 7) date.beginning_of_day # => Mon Jun 07 00:00:00 +0200 2010 ">Copy</button> </div> <p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-i-end_of_day"><code>end_of_day</code></a> returns a timestamp at the end of the day (23:59:59):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="n">date</span><span class="p">.</span><span class="nf">end_of_day</span> <span class="c1"># => Mon Jun 07 23:59:59 +0200 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = Date.new(2010, 6, 7) date.end_of_day # => Mon Jun 07 23:59:59 +0200 2010 ">Copy</button> </div> <p><code>beginning_of_day</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-i-at_beginning_of_day"><code>at_beginning_of_day</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-i-midnight"><code>midnight</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-i-at_midnight"><code>at_midnight</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date/calculations.rb">active_support/core_ext/date/calculations.rb</a></code>.</p></div><h5 id="beginning-of-hour-end-of-hour"><a class="anchorlink" href="#beginning-of-hour-end-of-hour" data-turbo="false"><span>15.1.6.2</span> <code>beginning_of_hour</code>, <code>end_of_hour</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-beginning_of_hour"><code>beginning_of_hour</code></a> returns a timestamp at the beginning of the hour (hh:00:00):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">19</span><span class="p">,</span> <span class="mi">55</span><span class="p">,</span> <span class="mi">25</span><span class="p">)</span> <span class="n">date</span><span class="p">.</span><span class="nf">beginning_of_hour</span> <span class="c1"># => Mon Jun 07 19:00:00 +0200 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = DateTime.new(2010, 6, 7, 19, 55, 25) date.beginning_of_hour # => Mon Jun 07 19:00:00 +0200 2010 ">Copy</button> </div> <p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-end_of_hour"><code>end_of_hour</code></a> returns a timestamp at the end of the hour (hh:59:59):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">19</span><span class="p">,</span> <span class="mi">55</span><span class="p">,</span> <span class="mi">25</span><span class="p">)</span> <span class="n">date</span><span class="p">.</span><span class="nf">end_of_hour</span> <span class="c1"># => Mon Jun 07 19:59:59 +0200 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = DateTime.new(2010, 6, 7, 19, 55, 25) date.end_of_hour # => Mon Jun 07 19:59:59 +0200 2010 ">Copy</button> </div> <p><code>beginning_of_hour</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-at_beginning_of_hour"><code>at_beginning_of_hour</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_time/calculations.rb">active_support/core_ext/date_time/calculations.rb</a></code>.</p></div><h5 id="beginning-of-minute-end-of-minute"><a class="anchorlink" href="#beginning-of-minute-end-of-minute" data-turbo="false"><span>15.1.6.3</span> <code>beginning_of_minute</code>, <code>end_of_minute</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-beginning_of_minute"><code>beginning_of_minute</code></a> returns a timestamp at the beginning of the minute (hh:mm:00):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">19</span><span class="p">,</span> <span class="mi">55</span><span class="p">,</span> <span class="mi">25</span><span class="p">)</span> <span class="n">date</span><span class="p">.</span><span class="nf">beginning_of_minute</span> <span class="c1"># => Mon Jun 07 19:55:00 +0200 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = DateTime.new(2010, 6, 7, 19, 55, 25) date.beginning_of_minute # => Mon Jun 07 19:55:00 +0200 2010 ">Copy</button> </div> <p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-end_of_minute"><code>end_of_minute</code></a> returns a timestamp at the end of the minute (hh:mm:59):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">19</span><span class="p">,</span> <span class="mi">55</span><span class="p">,</span> <span class="mi">25</span><span class="p">)</span> <span class="n">date</span><span class="p">.</span><span class="nf">end_of_minute</span> <span class="c1"># => Mon Jun 07 19:55:59 +0200 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = DateTime.new(2010, 6, 7, 19, 55, 25) date.end_of_minute # => Mon Jun 07 19:55:59 +0200 2010 ">Copy</button> </div> <p><code>beginning_of_minute</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-at_beginning_of_minute"><code>at_beginning_of_minute</code></a>.</p><div class="interstitial info"><p><code>beginning_of_hour</code>, <code>end_of_hour</code>, <code>beginning_of_minute</code>, and <code>end_of_minute</code> are implemented for <code>Time</code> and <code>DateTime</code> but <strong>not</strong> <code>Date</code> as it does not make sense to request the beginning or end of an hour or minute on a <code>Date</code> instance.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_time/calculations.rb">active_support/core_ext/date_time/calculations.rb</a></code>.</p></div><h5 id="ago-since"><a class="anchorlink" href="#ago-since" data-turbo="false"><span>15.1.6.4</span> <code>ago</code>, <code>since</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-i-ago"><code>ago</code></a> receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Fri, 11 Jun 2010</span> <span class="n">date</span><span class="p">.</span><span class="nf">ago</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => Thu, 10 Jun 2010 23:59:59 EDT -04:00</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = Date.current # => Fri, 11 Jun 2010 date.ago(1) # => Thu, 10 Jun 2010 23:59:59 EDT -04:00 ">Copy</button> </div> <p>Similarly, <a href="https://api.rubyonrails.org/v8.0.0/classes/Date.html#method-i-since"><code>since</code></a> moves forward:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">date</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Fri, 11 Jun 2010</span> <span class="n">date</span><span class="p">.</span><span class="nf">since</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => Fri, 11 Jun 2010 00:00:01 EDT -04:00</span> </code></pre> <button class="clipboard-button" data-clipboard-text="date = Date.current # => Fri, 11 Jun 2010 date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date/calculations.rb">active_support/core_ext/date/calculations.rb</a></code>.</p></div><h2 id="extensions-to-datetime"><a class="anchorlink" href="#extensions-to-datetime" data-turbo="false"><span>16</span> Extensions to <code>DateTime</code></a></h2><div class="interstitial warning"><p><code>DateTime</code> is not aware of DST rules and so some of these methods have edge cases when a DST change is going on. For example <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-seconds_since_midnight"><code>seconds_since_midnight</code></a> might not return the real amount in such a day.</p></div><h3 id="extensions-to-datetime-calculations"><a class="anchorlink" href="#extensions-to-datetime-calculations" data-turbo="false"><span>16.1</span> Calculations</a></h3><p>The class <code>DateTime</code> is a subclass of <code>Date</code> so by loading <code>active_support/core_ext/date/calculations.rb</code> you inherit these methods and their aliases, except that they will always return datetimes.</p><p>The following methods are reimplemented so you do <strong>not</strong> need to load <code>active_support/core_ext/date/calculations.rb</code> for these ones:</p> <ul> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-beginning_of_day"><code>beginning_of_day</code></a> / <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-midnight"><code>midnight</code></a> / <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-at_midnight"><code>at_midnight</code></a> / <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-at_beginning_of_day"><code>at_beginning_of_day</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-end_of_day"><code>end_of_day</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-ago"><code>ago</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-since"><code>since</code></a> / <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-in"><code>in</code></a></li> </ul> <p>On the other hand, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-advance"><code>advance</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-change"><code>change</code></a> are also defined and support more options, they are documented below.</p><p>The following methods are only implemented in <code>active_support/core_ext/date_time/calculations.rb</code> as they only make sense when used with a <code>DateTime</code> instance:</p> <ul> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-beginning_of_hour"><code>beginning_of_hour</code></a> / <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-at_beginning_of_hour"><code>at_beginning_of_hour</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-end_of_hour"><code>end_of_hour</code></a></li> </ul> <h4 id="named-datetimes"><a class="anchorlink" href="#named-datetimes" data-turbo="false"><span>16.1.1</span> Named Datetimes</a></h4><h5 id="datetime-current"><a class="anchorlink" href="#datetime-current" data-turbo="false"><span>16.1.1.1</span> <code>DateTime.current</code></a></h5><p>Active Support defines <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-c-current"><code>DateTime.current</code></a> to be like <code>Time.now.to_datetime</code>, except that it honors the user time zone, if defined. The instance predicates <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-past-3F"><code>past?</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-future-3F"><code>future?</code></a> are defined relative to <code>DateTime.current</code>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_time/calculations.rb">active_support/core_ext/date_time/calculations.rb</a></code>.</p></div><h4 id="other-extensions"><a class="anchorlink" href="#other-extensions" data-turbo="false"><span>16.1.2</span> Other Extensions</a></h4><h5 id="seconds-since-midnight"><a class="anchorlink" href="#seconds-since-midnight" data-turbo="false"><span>16.1.2.1</span> <code>seconds_since_midnight</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-seconds_since_midnight"><code>seconds_since_midnight</code></a> returns the number of seconds since midnight:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Mon, 07 Jun 2010 20:26:36 +0000</span> <span class="n">now</span><span class="p">.</span><span class="nf">seconds_since_midnight</span> <span class="c1"># => 73596</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now = DateTime.current # => Mon, 07 Jun 2010 20:26:36 +0000 now.seconds_since_midnight # => 73596 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_time/calculations.rb">active_support/core_ext/date_time/calculations.rb</a></code>.</p></div><h5 id="utc"><a class="anchorlink" href="#utc" data-turbo="false"><span>16.1.2.2</span> <code>utc</code></a></h5><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-utc"><code>utc</code></a> gives you the same datetime in the receiver expressed in UTC.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Mon, 07 Jun 2010 19:27:52 -0400</span> <span class="n">now</span><span class="p">.</span><span class="nf">utc</span> <span class="c1"># => Mon, 07 Jun 2010 23:27:52 +0000</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now = DateTime.current # => Mon, 07 Jun 2010 19:27:52 -0400 now.utc # => Mon, 07 Jun 2010 23:27:52 +0000 ">Copy</button> </div> <p>This method is also aliased as <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-getutc"><code>getutc</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_time/calculations.rb">active_support/core_ext/date_time/calculations.rb</a></code>.</p></div><h5 id="utc-questionmark"><a class="anchorlink" href="#utc-questionmark" data-turbo="false"><span>16.1.2.3</span> <code>utc?</code></a></h5><p>The predicate <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-utc-3F"><code>utc?</code></a> says whether the receiver has UTC as its time zone:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">now</span> <span class="c1"># => Mon, 07 Jun 2010 19:30:47 -0400</span> <span class="n">now</span><span class="p">.</span><span class="nf">utc?</span> <span class="c1"># => false</span> <span class="n">now</span><span class="p">.</span><span class="nf">utc</span><span class="p">.</span><span class="nf">utc?</span> <span class="c1"># => true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400 now.utc? # => false now.utc.utc? # => true ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_time/calculations.rb">active_support/core_ext/date_time/calculations.rb</a></code>.</p></div><h5 id="other-extensions-advance"><a class="anchorlink" href="#other-extensions-advance" data-turbo="false"><span>16.1.2.4</span> <code>advance</code></a></h5><p>The most generic way to jump to another datetime is <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-advance"><code>advance</code></a>. This method receives a hash with keys <code>:years</code>, <code>:months</code>, <code>:weeks</code>, <code>:days</code>, <code>:hours</code>, <code>:minutes</code>, and <code>:seconds</code>, and returns a datetime advanced as much as the present keys indicate.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Thu, 05 Aug 2010 11:33:31 +0000</span> <span class="n">d</span><span class="p">.</span><span class="nf">advance</span><span class="p">(</span><span class="ss">years: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">months: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">days: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">hours: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">minutes: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">seconds: </span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => Tue, 06 Sep 2011 12:34:32 +0000</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = DateTime.current # => Thu, 05 Aug 2010 11:33:31 +0000 d.advance(years: 1, months: 1, days: 1, hours: 1, minutes: 1, seconds: 1) # => Tue, 06 Sep 2011 12:34:32 +0000 ">Copy</button> </div> <p>This method first computes the destination date passing <code>:years</code>, <code>:months</code>, <code>:weeks</code>, and <code>:days</code> to <code>Date#advance</code> documented above. After that, it adjusts the time calling <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-since"><code>since</code></a> with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in <code>Date#advance</code> applies, and we can extend it to show order relevance related to the time bits.</p><p>If we first move the date bits (that have also a relative order of processing, as documented before), and then the time bits we get for example the following computation:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">28</span><span class="p">,</span> <span class="mi">23</span><span class="p">,</span> <span class="mi">59</span><span class="p">,</span> <span class="mi">59</span><span class="p">)</span> <span class="c1"># => Sun, 28 Feb 2010 23:59:59 +0000</span> <span class="n">d</span><span class="p">.</span><span class="nf">advance</span><span class="p">(</span><span class="ss">months: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">seconds: </span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => Mon, 29 Mar 2010 00:00:00 +0000</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d = DateTime.new(2010, 2, 28, 23, 59, 59) # => Sun, 28 Feb 2010 23:59:59 +0000 d.advance(months: 1, seconds: 1) # => Mon, 29 Mar 2010 00:00:00 +0000 ">Copy</button> </div> <p>but if we computed them the other way around, the result would be different:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">d</span><span class="p">.</span><span class="nf">advance</span><span class="p">(</span><span class="ss">seconds: </span><span class="mi">1</span><span class="p">).</span><span class="nf">advance</span><span class="p">(</span><span class="ss">months: </span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => Thu, 01 Apr 2010 00:00:00 +0000</span> </code></pre> <button class="clipboard-button" data-clipboard-text="d.advance(seconds: 1).advance(months: 1) # => Thu, 01 Apr 2010 00:00:00 +0000 ">Copy</button> </div> <div class="interstitial warning"><p>Since <code>DateTime</code> is not DST-aware you can end up in a non-existing point in time with no warning or error telling you so.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_time/calculations.rb">active_support/core_ext/date_time/calculations.rb</a></code>.</p></div><h4 id="extensions-to-datetime-calculations-changing-components"><a class="anchorlink" href="#extensions-to-datetime-calculations-changing-components" data-turbo="false"><span>16.1.3</span> Changing Components</a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateTime.html#method-i-change"><code>change</code></a> allows you to get a new datetime which is the same as the receiver except for the given options, which may include <code>:year</code>, <code>:month</code>, <code>:day</code>, <code>:hour</code>, <code>:min</code>, <code>:sec</code>, <code>:offset</code>, <code>:start</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Tue, 08 Jun 2010 01:56:22 +0000</span> <span class="n">now</span><span class="p">.</span><span class="nf">change</span><span class="p">(</span><span class="ss">year: </span><span class="mi">2011</span><span class="p">,</span> <span class="ss">offset: </span><span class="no">Rational</span><span class="p">(</span><span class="o">-</span><span class="mi">6</span><span class="p">,</span> <span class="mi">24</span><span class="p">))</span> <span class="c1"># => Wed, 08 Jun 2011 01:56:22 -0600</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now = DateTime.current # => Tue, 08 Jun 2010 01:56:22 +0000 now.change(year: 2011, offset: Rational(-6, 24)) # => Wed, 08 Jun 2011 01:56:22 -0600 ">Copy</button> </div> <p>If hours are zeroed, then minutes and seconds are too (unless they have given values):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span><span class="p">.</span><span class="nf">change</span><span class="p">(</span><span class="ss">hour: </span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => Tue, 08 Jun 2010 00:00:00 +0000</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now.change(hour: 0) # => Tue, 08 Jun 2010 00:00:00 +0000 ">Copy</button> </div> <p>Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span><span class="p">.</span><span class="nf">change</span><span class="p">(</span><span class="ss">min: </span><span class="mi">0</span><span class="p">)</span> <span class="c1"># => Tue, 08 Jun 2010 01:00:00 +0000</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now.change(min: 0) # => Tue, 08 Jun 2010 01:00:00 +0000 ">Copy</button> </div> <p>This method is not tolerant to non-existing dates, if the change is invalid <code>ArgumentError</code> is raised:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">DateTime</span><span class="p">.</span><span class="nf">current</span><span class="p">.</span><span class="nf">change</span><span class="p">(</span><span class="ss">month: </span><span class="mi">2</span><span class="p">,</span> <span class="ss">day: </span><span class="mi">30</span><span class="p">)</span> <span class="c1"># => ArgumentError: invalid date</span> </code></pre> <button class="clipboard-button" data-clipboard-text="DateTime.current.change(month: 2, day: 30) # => ArgumentError: invalid date ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_time/calculations.rb">active_support/core_ext/date_time/calculations.rb</a></code>.</p></div><h4 id="extensions-to-datetime-calculations-durations"><a class="anchorlink" href="#extensions-to-datetime-calculations-durations" data-turbo="false"><span>16.1.4</span> Durations</a></h4><p><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Duration.html"><code>Duration</code></a> objects can be added to and subtracted from datetimes:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span> <span class="o">=</span> <span class="no">DateTime</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Mon, 09 Aug 2010 23:15:17 +0000</span> <span class="n">now</span> <span class="o">+</span> <span class="mi">1</span><span class="p">.</span><span class="nf">year</span> <span class="c1"># => Tue, 09 Aug 2011 23:15:17 +0000</span> <span class="n">now</span> <span class="o">-</span> <span class="mi">1</span><span class="p">.</span><span class="nf">week</span> <span class="c1"># => Mon, 02 Aug 2010 23:15:17 +0000</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now = DateTime.current # => Mon, 09 Aug 2010 23:15:17 +0000 now + 1.year # => Tue, 09 Aug 2011 23:15:17 +0000 now - 1.week # => Mon, 02 Aug 2010 23:15:17 +0000 ">Copy</button> </div> <p>They translate to calls to <code>since</code> or <code>advance</code>. For example here we get the correct jump in the calendar reform:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">DateTime</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">1582</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">23</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">.</span><span class="nf">hour</span> <span class="c1"># => Fri, 15 Oct 1582 00:00:00 +0000</span> </code></pre> <button class="clipboard-button" data-clipboard-text="DateTime.new(1582, 10, 4, 23) + 1.hour # => Fri, 15 Oct 1582 00:00:00 +0000 ">Copy</button> </div> <h2 id="extensions-to-time"><a class="anchorlink" href="#extensions-to-time" data-turbo="false"><span>17</span> Extensions to <code>Time</code></a></h2><h3 id="calculations"><a class="anchorlink" href="#calculations" data-turbo="false"><span>17.1</span> Calculations</a></h3><p>They are analogous. Please refer to their documentation above and take into account the following differences:</p> <ul> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-i-change"><code>change</code></a> accepts an additional <code>:usec</code> option.</li> <li><code>Time</code> understands DST, so you get correct DST calculations as in</li> </ul> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Time</span><span class="p">.</span><span class="nf">zone_default</span> <span class="c1"># => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...></span> <span class="c1"># In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.</span> <span class="n">t</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">local</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">28</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">59</span><span class="p">,</span> <span class="mi">59</span><span class="p">)</span> <span class="c1"># => Sun Mar 28 01:59:59 +0100 2010</span> <span class="n">t</span><span class="p">.</span><span class="nf">advance</span><span class="p">(</span><span class="ss">seconds: </span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => Sun Mar 28 03:00:00 +0200 2010</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Time.zone_default # => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...> # In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST. t = Time.local(2010, 3, 28, 1, 59, 59) # => Sun Mar 28 01:59:59 +0100 2010 t.advance(seconds: 1) # => Sun Mar 28 03:00:00 +0200 2010 ">Copy</button> </div> <ul> <li>If <a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-i-since"><code>since</code></a> or <a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-i-ago"><code>ago</code></a> jumps to a time that can't be expressed with <code>Time</code> a <code>DateTime</code> object is returned instead.</li> </ul> <h4 id="time-current"><a class="anchorlink" href="#time-current" data-turbo="false"><span>17.1.1</span> <code>Time.current</code></a></h4><p>Active Support defines <a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-c-current"><code>Time.current</code></a> to be today in the current time zone. That's like <code>Time.now</code>, except that it honors the user time zone, if defined. It also defines the instance predicates <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-past-3F"><code>past?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-today-3F"><code>today?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-tomorrow-3F"><code>tomorrow?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-next_day-3F"><code>next_day?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-yesterday-3F"><code>yesterday?</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-prev_day-3F"><code>prev_day?</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-future-3F"><code>future?</code></a>, all of them relative to <code>Time.current</code>.</p><p>When making Time comparisons using methods which honor the user time zone, make sure to use <code>Time.current</code> instead of <code>Time.now</code>. There are cases where the user time zone might be in the future compared to the system time zone, which <code>Time.now</code> uses by default. This means <code>Time.now.to_date</code> may equal <code>Date.yesterday</code>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/time/calculations.rb">active_support/core_ext/time/calculations.rb</a></code>.</p></div><h4 id="all-day-all-week-all-month-all-quarter-and-all-year"><a class="anchorlink" href="#all-day-all-week-all-month-all-quarter-and-all-year" data-turbo="false"><span>17.1.2</span> <code>all_day</code>, <code>all_week</code>, <code>all_month</code>, <code>all_quarter</code>, and <code>all_year</code></a></h4><p>The method <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-all_day"><code>all_day</code></a> returns a range representing the whole day of the current time.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Mon, 09 Aug 2010 23:20:05 UTC +00:00</span> <span class="n">now</span><span class="p">.</span><span class="nf">all_day</span> <span class="c1"># => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now = Time.current # => Mon, 09 Aug 2010 23:20:05 UTC +00:00 now.all_day # => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00 ">Copy</button> </div> <p>Analogously, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-all_week"><code>all_week</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-all_month"><code>all_month</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-all_quarter"><code>all_quarter</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-all_year"><code>all_year</code></a> all serve the purpose of generating time ranges.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Mon, 09 Aug 2010 23:20:05 UTC +00:00</span> <span class="n">now</span><span class="p">.</span><span class="nf">all_week</span> <span class="c1"># => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Sun, 15 Aug 2010 23:59:59 UTC +00:00</span> <span class="n">now</span><span class="p">.</span><span class="nf">all_week</span><span class="p">(</span><span class="ss">:sunday</span><span class="p">)</span> <span class="c1"># => Sun, 16 Sep 2012 00:00:00 UTC +00:00..Sat, 22 Sep 2012 23:59:59 UTC +00:00</span> <span class="n">now</span><span class="p">.</span><span class="nf">all_month</span> <span class="c1"># => Sat, 01 Aug 2010 00:00:00 UTC +00:00..Tue, 31 Aug 2010 23:59:59 UTC +00:00</span> <span class="n">now</span><span class="p">.</span><span class="nf">all_quarter</span> <span class="c1"># => Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +00:00</span> <span class="n">now</span><span class="p">.</span><span class="nf">all_year</span> <span class="c1"># => Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now = Time.current # => Mon, 09 Aug 2010 23:20:05 UTC +00:00 now.all_week # => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Sun, 15 Aug 2010 23:59:59 UTC +00:00 now.all_week(:sunday) # => Sun, 16 Sep 2012 00:00:00 UTC +00:00..Sat, 22 Sep 2012 23:59:59 UTC +00:00 now.all_month # => Sat, 01 Aug 2010 00:00:00 UTC +00:00..Tue, 31 Aug 2010 23:59:59 UTC +00:00 now.all_quarter # => Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +00:00 now.all_year # => Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h4 id="prev-day-next-day"><a class="anchorlink" href="#prev-day-next-day" data-turbo="false"><span>17.1.3</span> <code>prev_day</code>, <code>next_day</code></a></h4><p><a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-i-prev_day"><code>prev_day</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-i-next_day"><code>next_day</code></a> return the time in the last or next day:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">t</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="c1"># => 2010-05-08 00:00:00 +0900</span> <span class="n">t</span><span class="p">.</span><span class="nf">prev_day</span> <span class="c1"># => 2010-05-07 00:00:00 +0900</span> <span class="n">t</span><span class="p">.</span><span class="nf">next_day</span> <span class="c1"># => 2010-05-09 00:00:00 +0900</span> </code></pre> <button class="clipboard-button" data-clipboard-text="t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 t.prev_day # => 2010-05-07 00:00:00 +0900 t.next_day # => 2010-05-09 00:00:00 +0900 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/time/calculations.rb">active_support/core_ext/time/calculations.rb</a></code>.</p></div><h4 id="prev-month-next-month"><a class="anchorlink" href="#prev-month-next-month" data-turbo="false"><span>17.1.4</span> <code>prev_month</code>, <code>next_month</code></a></h4><p><a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-i-prev_month"><code>prev_month</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-i-next_month"><code>next_month</code></a> return the time with the same day in the last or next month:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">t</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="c1"># => 2010-05-08 00:00:00 +0900</span> <span class="n">t</span><span class="p">.</span><span class="nf">prev_month</span> <span class="c1"># => 2010-04-08 00:00:00 +0900</span> <span class="n">t</span><span class="p">.</span><span class="nf">next_month</span> <span class="c1"># => 2010-06-08 00:00:00 +0900</span> </code></pre> <button class="clipboard-button" data-clipboard-text="t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 t.prev_month # => 2010-04-08 00:00:00 +0900 t.next_month # => 2010-06-08 00:00:00 +0900 ">Copy</button> </div> <p>If such a day does not exist, the last day of the corresponding month is returned:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Time</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">prev_month</span> <span class="c1"># => 2000-04-30 00:00:00 +0900</span> <span class="no">Time</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">prev_month</span> <span class="c1"># => 2000-02-29 00:00:00 +0900</span> <span class="no">Time</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">next_month</span> <span class="c1"># => 2000-06-30 00:00:00 +0900</span> <span class="no">Time</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">next_month</span> <span class="c1"># => 2000-02-29 00:00:00 +0900</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Time.new(2000, 5, 31).prev_month # => 2000-04-30 00:00:00 +0900 Time.new(2000, 3, 31).prev_month # => 2000-02-29 00:00:00 +0900 Time.new(2000, 5, 31).next_month # => 2000-06-30 00:00:00 +0900 Time.new(2000, 1, 31).next_month # => 2000-02-29 00:00:00 +0900 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/time/calculations.rb">active_support/core_ext/time/calculations.rb</a></code>.</p></div><h4 id="prev-year-next-year"><a class="anchorlink" href="#prev-year-next-year" data-turbo="false"><span>17.1.5</span> <code>prev_year</code>, <code>next_year</code></a></h4><p><a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-i-prev_year"><code>prev_year</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-i-next_year"><code>next_year</code></a> return a time with the same day/month in the last or next year:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">t</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="c1"># => 2010-05-08 00:00:00 +0900</span> <span class="n">t</span><span class="p">.</span><span class="nf">prev_year</span> <span class="c1"># => 2009-05-08 00:00:00 +0900</span> <span class="n">t</span><span class="p">.</span><span class="nf">next_year</span> <span class="c1"># => 2011-05-08 00:00:00 +0900</span> </code></pre> <button class="clipboard-button" data-clipboard-text="t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 t.prev_year # => 2009-05-08 00:00:00 +0900 t.next_year # => 2011-05-08 00:00:00 +0900 ">Copy</button> </div> <p>If date is the 29th of February of a leap year, you obtain the 28th:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">t</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">29</span><span class="p">)</span> <span class="c1"># => 2000-02-29 00:00:00 +0900</span> <span class="n">t</span><span class="p">.</span><span class="nf">prev_year</span> <span class="c1"># => 1999-02-28 00:00:00 +0900</span> <span class="n">t</span><span class="p">.</span><span class="nf">next_year</span> <span class="c1"># => 2001-02-28 00:00:00 +0900</span> </code></pre> <button class="clipboard-button" data-clipboard-text="t = Time.new(2000, 2, 29) # => 2000-02-29 00:00:00 +0900 t.prev_year # => 1999-02-28 00:00:00 +0900 t.next_year # => 2001-02-28 00:00:00 +0900 ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/time/calculations.rb">active_support/core_ext/time/calculations.rb</a></code>.</p></div><h4 id="prev-quarter-next-quarter"><a class="anchorlink" href="#prev-quarter-next-quarter" data-turbo="false"><span>17.1.6</span> <code>prev_quarter</code>, <code>next_quarter</code></a></h4><p><a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-prev_quarter"><code>prev_quarter</code></a> and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-next_quarter"><code>next_quarter</code></a> return the date with the same day in the previous or next quarter:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">t</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">local</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="c1"># => 2010-05-08 00:00:00 +0300</span> <span class="n">t</span><span class="p">.</span><span class="nf">prev_quarter</span> <span class="c1"># => 2010-02-08 00:00:00 +0200</span> <span class="n">t</span><span class="p">.</span><span class="nf">next_quarter</span> <span class="c1"># => 2010-08-08 00:00:00 +0300</span> </code></pre> <button class="clipboard-button" data-clipboard-text="t = Time.local(2010, 5, 8) # => 2010-05-08 00:00:00 +0300 t.prev_quarter # => 2010-02-08 00:00:00 +0200 t.next_quarter # => 2010-08-08 00:00:00 +0300 ">Copy</button> </div> <p>If such a day does not exist, the last day of the corresponding month is returned:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Time</span><span class="p">.</span><span class="nf">local</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">prev_quarter</span> <span class="c1"># => 2000-04-30 00:00:00 +0300</span> <span class="no">Time</span><span class="p">.</span><span class="nf">local</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">prev_quarter</span> <span class="c1"># => 2000-02-29 00:00:00 +0200</span> <span class="no">Time</span><span class="p">.</span><span class="nf">local</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">prev_quarter</span> <span class="c1"># => 2000-07-31 00:00:00 +0300</span> <span class="no">Time</span><span class="p">.</span><span class="nf">local</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">31</span><span class="p">).</span><span class="nf">next_quarter</span> <span class="c1"># => 2001-03-01 00:00:00 +0200</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Time.local(2000, 7, 31).prev_quarter # => 2000-04-30 00:00:00 +0300 Time.local(2000, 5, 31).prev_quarter # => 2000-02-29 00:00:00 +0200 Time.local(2000, 10, 31).prev_quarter # => 2000-07-31 00:00:00 +0300 Time.local(2000, 11, 31).next_quarter # => 2001-03-01 00:00:00 +0200 ">Copy</button> </div> <p><code>prev_quarter</code> is aliased to <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-last_quarter"><code>last_quarter</code></a>.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb">active_support/core_ext/date_and_time/calculations.rb</a></code>.</p></div><h3 id="time-constructors"><a class="anchorlink" href="#time-constructors" data-turbo="false"><span>17.2</span> Time Constructors</a></h3><p>Active Support defines <a href="https://api.rubyonrails.org/v8.0.0/classes/Time.html#method-c-current"><code>Time.current</code></a> to be <code>Time.zone.now</code> if there's a user time zone defined, with fallback to <code>Time.now</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Time</span><span class="p">.</span><span class="nf">zone_default</span> <span class="c1"># => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...></span> <span class="no">Time</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Fri, 06 Aug 2010 17:11:58 CEST +02:00</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Time.zone_default # => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...> Time.current # => Fri, 06 Aug 2010 17:11:58 CEST +02:00 ">Copy</button> </div> <p>Analogously to <code>DateTime</code>, the predicates <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-past-3F"><code>past?</code></a>, and <a href="https://api.rubyonrails.org/v8.0.0/classes/DateAndTime/Calculations.html#method-i-future-3F"><code>future?</code></a> are relative to <code>Time.current</code>.</p><p>If the time to be constructed lies beyond the range supported by <code>Time</code> in the runtime platform, usecs are discarded and a <code>DateTime</code> object is returned instead.</p><h4 id="durations"><a class="anchorlink" href="#durations" data-turbo="false"><span>17.2.1</span> Durations</a></h4><p><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Duration.html"><code>Duration</code></a> objects can be added to and subtracted from time objects:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">now</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">current</span> <span class="c1"># => Mon, 09 Aug 2010 23:20:05 UTC +00:00</span> <span class="n">now</span> <span class="o">+</span> <span class="mi">1</span><span class="p">.</span><span class="nf">year</span> <span class="c1"># => Tue, 09 Aug 2011 23:21:11 UTC +00:00</span> <span class="n">now</span> <span class="o">-</span> <span class="mi">1</span><span class="p">.</span><span class="nf">week</span> <span class="c1"># => Mon, 02 Aug 2010 23:21:11 UTC +00:00</span> </code></pre> <button class="clipboard-button" data-clipboard-text="now = Time.current # => Mon, 09 Aug 2010 23:20:05 UTC +00:00 now + 1.year # => Tue, 09 Aug 2011 23:21:11 UTC +00:00 now - 1.week # => Mon, 02 Aug 2010 23:21:11 UTC +00:00 ">Copy</button> </div> <p>They translate to calls to <code>since</code> or <code>advance</code>. For example here we get the correct jump in the calendar reform:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Time</span><span class="p">.</span><span class="nf">utc</span><span class="p">(</span><span class="mi">1582</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="o">+</span> <span class="mi">5</span><span class="p">.</span><span class="nf">days</span> <span class="c1"># => Mon Oct 18 00:00:00 UTC 1582</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Time.utc(1582, 10, 3) + 5.days # => Mon Oct 18 00:00:00 UTC 1582 ">Copy</button> </div> <h2 id="extensions-to-file"><a class="anchorlink" href="#extensions-to-file" data-turbo="false"><span>18</span> Extensions to <code>File</code></a></h2><h3 id="atomic-write"><a class="anchorlink" href="#atomic-write" data-turbo="false"><span>18.1</span> <code>atomic_write</code></a></h3><p>With the class method <a href="https://api.rubyonrails.org/v8.0.0/classes/File.html#method-c-atomic_write"><code>File.atomic_write</code></a> you can write to a file in a way that will prevent any reader from seeing half-written content.</p><p>The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done <code>atomic_write</code> closes the file handle and completes its job.</p><p>For example, Action Pack uses this method to write asset cache files like <code>all.css</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">File</span><span class="p">.</span><span class="nf">atomic_write</span><span class="p">(</span><span class="n">joined_asset_path</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">cache</span><span class="o">|</span> <span class="n">cache</span><span class="p">.</span><span class="nf">write</span><span class="p">(</span><span class="n">join_asset_file_contents</span><span class="p">(</span><span class="n">asset_paths</span><span class="p">))</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="File.atomic_write(joined_asset_path) do |cache| cache.write(join_asset_file_contents(asset_paths)) end ">Copy</button> </div> <p>To accomplish this <code>atomic_write</code> creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists <code>atomic_write</code> overwrites it and keeps owners and permissions. However there are a few cases where <code>atomic_write</code> cannot change the file ownership or permissions, this error is caught and skipped over trusting in the user/filesystem to ensure the file is accessible to the processes that need it.</p><div class="interstitial note"><p>Due to the chmod operation <code>atomic_write</code> performs, if the target file has an ACL set on it this ACL will be recalculated/modified.</p></div><div class="interstitial warning"><p>Note you can't append with <code>atomic_write</code>.</p></div><p>The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/file/atomic.rb">active_support/core_ext/file/atomic.rb</a></code>.</p></div><h2 id="extensions-to-nameerror"><a class="anchorlink" href="#extensions-to-nameerror" data-turbo="false"><span>19</span> Extensions to <code>NameError</code></a></h2><p>Active Support adds <a href="https://api.rubyonrails.org/v8.0.0/classes/NameError.html#method-i-missing_name-3F"><code>missing_name?</code></a> to <code>NameError</code>, which tests whether the exception was raised because of the name passed as argument.</p><p>The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully qualified constant name.</p><div class="interstitial info"><p>A symbol can represent a fully qualified constant name as in <code>:"ActiveRecord::Base"</code>, so the behavior for symbols is defined for convenience, not because it has to be that way technically.</p></div><p>For example, when an action of <code>ArticlesController</code> is called Rails tries optimistically to use <code>ArticlesHelper</code>. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that <code>articles_helper.rb</code> raises a <code>NameError</code> due to an actual unknown constant. That should be reraised. The method <code>missing_name?</code> provides a way to distinguish both cases:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">default_helper_module!</span> <span class="n">module_name</span> <span class="o">=</span> <span class="nb">name</span><span class="p">.</span><span class="nf">delete_suffix</span><span class="p">(</span><span class="s2">"Controller"</span><span class="p">)</span> <span class="n">module_path</span> <span class="o">=</span> <span class="n">module_name</span><span class="p">.</span><span class="nf">underscore</span> <span class="n">helper</span> <span class="n">module_path</span> <span class="k">rescue</span> <span class="no">LoadError</span> <span class="o">=></span> <span class="n">e</span> <span class="k">raise</span> <span class="n">e</span> <span class="k">unless</span> <span class="n">e</span><span class="p">.</span><span class="nf">is_missing?</span> <span class="s2">"helpers/</span><span class="si">#{</span><span class="n">module_path</span><span class="si">}</span><span class="s2">_helper"</span> <span class="k">rescue</span> <span class="no">NameError</span> <span class="o">=></span> <span class="n">e</span> <span class="k">raise</span> <span class="n">e</span> <span class="k">unless</span> <span class="n">e</span><span class="p">.</span><span class="nf">missing_name?</span> <span class="s2">"</span><span class="si">#{</span><span class="n">module_name</span><span class="si">}</span><span class="s2">Helper"</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def default_helper_module! module_name = name.delete_suffix("Controller") module_path = module_name.underscore helper module_path rescue LoadError => e raise e unless e.is_missing? "helpers/#{module_path}_helper" rescue NameError => e raise e unless e.missing_name? "#{module_name}Helper" end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/name_error.rb">active_support/core_ext/name_error.rb</a></code>.</p></div><h2 id="extensions-to-loaderror"><a class="anchorlink" href="#extensions-to-loaderror" data-turbo="false"><span>20</span> Extensions to <code>LoadError</code></a></h2><p>Active Support adds <a href="https://api.rubyonrails.org/v8.0.0/classes/LoadError.html#method-i-is_missing-3F"><code>is_missing?</code></a> to <code>LoadError</code>.</p><p>Given a path name <code>is_missing?</code> tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).</p><p>For example, when an action of <code>ArticlesController</code> is called Rails tries to load <code>articles_helper.rb</code>, but that file may not exist. That's fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method <code>is_missing?</code> provides a way to distinguish both cases:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">default_helper_module!</span> <span class="n">module_name</span> <span class="o">=</span> <span class="nb">name</span><span class="p">.</span><span class="nf">delete_suffix</span><span class="p">(</span><span class="s2">"Controller"</span><span class="p">)</span> <span class="n">module_path</span> <span class="o">=</span> <span class="n">module_name</span><span class="p">.</span><span class="nf">underscore</span> <span class="n">helper</span> <span class="n">module_path</span> <span class="k">rescue</span> <span class="no">LoadError</span> <span class="o">=></span> <span class="n">e</span> <span class="k">raise</span> <span class="n">e</span> <span class="k">unless</span> <span class="n">e</span><span class="p">.</span><span class="nf">is_missing?</span> <span class="s2">"helpers/</span><span class="si">#{</span><span class="n">module_path</span><span class="si">}</span><span class="s2">_helper"</span> <span class="k">rescue</span> <span class="no">NameError</span> <span class="o">=></span> <span class="n">e</span> <span class="k">raise</span> <span class="n">e</span> <span class="k">unless</span> <span class="n">e</span><span class="p">.</span><span class="nf">missing_name?</span> <span class="s2">"</span><span class="si">#{</span><span class="n">module_name</span><span class="si">}</span><span class="s2">Helper"</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def default_helper_module! module_name = name.delete_suffix("Controller") module_path = module_name.underscore helper module_path rescue LoadError => e raise e unless e.is_missing? "helpers/#{module_path}_helper" rescue NameError => e raise e unless e.missing_name? "#{module_name}Helper" end ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/load_error.rb">active_support/core_ext/load_error.rb</a></code>.</p></div><h2 id="extensions-to-pathname"><a class="anchorlink" href="#extensions-to-pathname" data-turbo="false"><span>21</span> Extensions to Pathname</a></h2><h3 id="existence"><a class="anchorlink" href="#existence" data-turbo="false"><span>21.1</span> <code>existence</code></a></h3><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/Pathname.html#method-i-existence"><code>existence</code></a> method returns the receiver if the named file exists otherwise returns <code>nil</code>. It is useful for idioms like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">content</span> <span class="o">=</span> <span class="no">Pathname</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"file"</span><span class="p">).</span><span class="nf">existence</span><span class="o">&</span><span class="p">.</span><span class="nf">read</span> </code></pre> <button class="clipboard-button" data-clipboard-text="content = Pathname.new("file").existence&.read ">Copy</button> </div> <div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/v8.0.0/activesupport/lib/active_support/core_ext/pathname/existence.rb">active_support/core_ext/pathname/existence.rb</a></code>.</p></div> </section> <hr> <footer aria-labelledby="heading-feedback" role="region"> <h2 id="heading-feedback">Feedback</h2> <p> You're encouraged to help improve the quality of this guide. </p> <p> Please contribute if you see any typos or factual errors. To get started, you can read our <a href="https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section. </p> <p> You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for main. Make sure to check <a href="https://edgeguides.rubyonrails.org">Edge Guides</a> first to verify if the issues are already fixed or not on the main branch. Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a> for style and conventions. </p> <p> If for whatever reason you spot something to fix but cannot patch it yourself, please <a href="https://github.com/rails/rails/issues">open an issue</a>. </p> <p>And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the <a href="https://discuss.rubyonrails.org/c/rubyonrails-docs">official Ruby on Rails Forum</a>. </p> </footer> </div> </article> </main> <hr class="hide" /> <footer id="complementary"> <div class="wrapper"> <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p> <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> </div> </footer> <a href="#main-skip-link" class="back-to-top" data-turbo="false"><span class="visibly-hidden">Back to top</span></a> </body> </html>