skip to content

Core Class Additions

Active Support reopens Ruby's core classes with blank? and present?, try, Duration arithmetic like 3.days.ago, String inflections and Module#delegate. Interviewers check you can tell Rails from Ruby.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In Rails, how do Active Support's blank?, present? and presence differ from Ruby's nil? and empty?, and what does each return?

level: juniorimportance: must knowfreq 72%

answer

  1. nil, false, empty, whitespace-only
  2. numbers are never blank
  3. present? is just !blank?
  4. presence returns self or nil
  5. nil.empty? raises NoMethodError

basics

~20 s

blank? is true for nil, false, whitespace-only strings and empty collections; present? is its negation; presence returns the receiver when present and nil otherwise. Ruby's nil? only matches nil, and empty? does not exist on nil.

solid answer

~40 s

Active Support defines `blank?` on every object: `nil`, `false`, `""`, `" "` (any Unicode whitespace), `[]`, `{}` and anything whose `empty?` is true are blank, while numbers, `true` and `Time` objects never are, so `0.blank?` is `false`. `present?` is simply `!blank?`. `presence` returns the receiver itself when it is present and `nil` otherwise, which makes `params[:city].presence || "Online"` a one-line default. Ruby's own `nil?` is true only for `nil`, and `empty?` exists only on strings, collections and the like: `" ".empty?` is `false` and `nil.empty?` raises `NoMethodError`. One trap: on an unloaded Active Record relation, `blank?` and `present?` load every record, so `exists?` is the cheaper check.

code

ruby · 9 lines
ruby
nil.blank?        # => true
"   ".blank?      # => true
"   ".empty?      # => false
0.blank?          # => false
[nil].blank?      # => false
{}.present?       # => false
"Berlin".presence # => "Berlin"
"".presence       # => nil
nil.empty?        # NoMethodError

go deeper

for a junior

Recall the blank list (nil, false, whitespace strings, empty collections), that numbers are never blank, and that presence returns the value or nil.

for a middle

Explain why nil.empty? fails while nil.blank? works, how the Object fallback uses empty?, and how presence replaces an if/else defaulting branch.

for a senior

Show you know present? on a relation loads every record, and pick exists? or any? when only the answer is needed.

for a principal

Weigh how far a codebase should lean on blank-style predicates versus normalizing input once at the boundary, for example stripping and nil-ing empty form fields before they are saved.

## What Active Support adds Ruby gives you two narrow predicates: `nil?`, which is true only for `nil`, and `empty?`, which strings, arrays, hashes and a few other classes define. Form input rarely fits either: a guest who types three spaces into the "dietary note" field sends a string that is neither `nil` nor empty. **Active Support** (loaded by every Rails app) reopens `Object` and several core classes to add three methods that answer the question an app actually asks: *is there anything here?* - **`blank?`**: true when the value carries no meaningful content. - **`present?`**: defined as `!blank?`, nothing more. - **`presence`**: returns the receiver when it is present, otherwise `nil`. ## What counts as blank | Value | `blank?` | Why | |---|---|---| | `nil`, `false` | true | `NilClass` and `FalseClass` define it as true | | `""`, `" "`, a tab or newline | true | `String#blank?` matches `/\A[[:space:]]*\z/`, so Unicode whitespace such as a non-breaking space counts | | `[]`, `{}`, `:""` | true | `Array`, `Hash` and `Symbol` alias `blank?` to `empty?` | | `0`, `0.0`, `true` | false | `Numeric#blank?` and `TrueClass#blank?` return false | | `Time.now` | false | `Time#blank?` returns false | | any other object | `empty?` if it responds to it, else false | the `Object#blank?` fallback | Two results surprise people. `0.blank?` is `false`: Rails does not treat zero as missing, so a quantity of zero guests survives a `present?` check. And `[nil].blank?` is `false`, because the array is not empty even though its only element is `nil`. ## `presence` as a defaulting tool `presence` is the method that removes most `if x.present?` branches. `object.presence` is equivalent to `object.present? ? object : nil`, so it chains with `||`: ```ruby class InvitationsController < ApplicationController def create venue = params[:venue].presence || "Online" note = params[:note].presence # " " becomes nil, not a blank string @invitation = Invitation.create!(venue: venue, note: note, event: Event.find(params[:event_id])) redirect_to @invitation end end ``` Without `presence`, an empty form field submits `""`, which is truthy in Ruby, so `params[:venue] || "Online"` would keep the empty string. The related `presence_in(list)` returns the receiver only when it is in the list, a quick allow-list for a sort parameter. ## How they differ from Ruby's predicates 1. **`nil?`** is Ruby's and asks only about `nil`. `"".nil?` and `false.nil?` are both `false`. 2. **`empty?`** is Ruby's and is defined per class. `" ".empty?` is `false` because the string has characters, and `nil.empty?` raises `NoMethodError` because `NilClass` has no such method. 3. **`blank?`** is Active Support's and is defined on every object, so it is safe to call on a value that might be `nil`. In a plain Ruby script without Active Support, `blank?` does not exist at all, which is a common way interviewers check that a candidate can tell Rails from Ruby. ## Where Rails itself relies on `blank?` The same rule powers validations. `validates :name, presence: true` adds the `:blank` error when the value is `blank?`, and `absence: true` adds `:present` when it is `present?`. Because `false.blank?` is `true`, a presence validation on a boolean column such as `plus_one_allowed` rejects a legitimate `false`; the documented alternative is `validates :plus_one_allowed, inclusion: { in: [true, false] }`. A whitespace-only name also fails presence, which is usually what you want. ## The relation trap An Active Record relation responds to `blank?` by loading its records: `Relation#blank?` is `records.blank?`, and `present?` is its negation, so `@event.guests.present?` in a controller instantiates every guest just to answer yes or no. If the view will iterate those guests anyway, that load is free, because the relation is now loaded. If it will not, `exists?` (or `any?` and `empty?`, which run an existence query when the relation is not loaded) answers with a `LIMIT 1` query instead. ## Pitfalls interviewers listen for - Treating `blank?` as Ruby core and calling it in a gem that never required Active Support. - Using `present?` to test a number and expecting `0` to fail it. - Writing `params[:x] || default` and keeping an empty string. - Calling `present?` on a large relation only to decide whether to render a section. - Assuming `presence` returns a boolean; it returns the value itself or `nil`.

  • Why can `@event.guests.present?` be slower than `@event.guests.exists?`?
    On an unloaded relation, `present?` calls `blank?`, which Active Record implements as `records.blank?`, so every matching row is fetched and turned into an object. `exists?` sends a `SELECT 1 ... LIMIT 1` query instead. If the page renders the guests anyway, `present?` is fine because the records are needed; if it only decides whether to show a heading, use `exists?` or `any?`.
  • When would you reach for `presence_in` rather than `presence`?
    When the value must come from a fixed list. `params[:sort].presence_in(%w[name rsvp_date])` returns the parameter only if it is one of those strings and `nil` otherwise, so `|| "name"` supplies a safe default. It raises `ArgumentError` if the argument does not respond to `include?`.

  • 0 and 0.0 are blank in Rails, just like an empty string.
  • A string of spaces is not blank because it has characters in it.
  • presence returns true or false, just like present?.
  • nil.empty? works the same way as nil.blank? does.
  • Calling present? on an Active Record relation always runs a cheap EXISTS query.
open as a page

In a Rails model, what does delegate :status, to: :rsvp, prefix: true, allow_nil: true generate, and what changes without allow_nil?

level: middleimportance: must knowfreq 52%

basics

~10 s

It defines rsvp_status, which calls rsvp.status and returns nil when rsvp is nil. Without allow_nil: a nil rsvp raises ActiveSupport::DelegationError, a NoMethodError subclass naming the method and the nil target.

open as a page

In Rails, how do Array#to_sentence and String inflections such as pluralize, tableize and parameterize turn guest data into readable text?

level: juniorimportance: should knowfreq 38%

basics

~10 s

to_sentence joins an array as "Ana, Ben, and Cy" with configurable, I18n-aware connectors. String inflections rewrite words: pluralize(count), singularize, camelize, underscore, tableize, classify, humanize, titleize and parameterize for slugs.

open as a page

In a Rails app, what does 2.weeks.ago return, and why can 1.day.from_now differ from 24.hours.from_now?

level: middleimportance: should knowfreq 50%

basics

~20 s

2.weeks is an ActiveSupport::Duration and .ago subtracts it from Time.current, giving a time two weeks back. Days, weeks, months and years move the calendar and keep the wall-clock time; hours move by exact seconds, so they diverge across DST.

open as a page

In Rails, how do Active Support's try and try! differ, and when is Ruby's safe navigation operator &. the better choice?

level: middleimportance: should knowfreq 45%

basics

~20 s

Both return nil when the receiver is nil. try also returns nil when a non-nil receiver lacks the public method; try! raises NoMethodError then. Ruby's &. behaves like try!, so prefer &. and keep try for duck-typed receivers.

open as a page

In a plain Ruby gem that requires only active_support, why does 3.days raise NoMethodError, and how should the gem load just the extensions it uses?

level: seniorimportance: should knowfreq 28%

basics

~20 s

require "active_support" loads only what the framework itself needs, not most core extensions; a Rails app gets them because boot requires active_support/all. A gem should require "active_support" and then each file it uses, such as active_support/core_ext/integer/time.

open as a page