In Rails, how do Active Support's blank?, present? and presence differ from Ruby's nil? and empty?, and what does each return?
answer
- nil, false, empty, whitespace-only
- numbers are never blank
- present? is just !blank?
- presence returns self or nil
- nil.empty? raises NoMethodError
basics
~20 sblank? 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 sActive 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 linesnil.blank? # => true
" ".blank? # => true
" ".empty? # => false
0.blank? # => false
[nil].blank? # => false
{}.present? # => false
"Berlin".presence # => "Berlin"
"".presence # => nil
nil.empty? # NoMethodErrorgo deeper
Recall the blank list (nil, false, whitespace strings, empty collections), that numbers are never blank, and that presence returns the value or nil.
Explain why nil.empty? fails while nil.blank? works, how the Object fallback uses empty?, and how presence replaces an if/else defaulting branch.
Show you know present? on a relation loads every record, and pick exists? or any? when only the answer is needed.
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.