ActiveRecord: Improving Readability with Array#inquiry

In Rails, we are used to using the .inquiry method on strings (like the famous Rails.env.development?). However, ActiveSupport also extends this functionality to Arrays, transforming a simple list into an object capable of answering questions semantically.

Array#inquiry is perfect for when you have a list of options and want to check for the presence of an item without using the traditional .include?.

The Problem: Repetitive and Unreadable Checks

Imagine you have an array of roles for a user. The standard way to check a permission would be:

1
2
3
4
5
roles = ["admin", "editor"]

if roles.include?("admin")
  # do something
end

It works, but it’s not very “Rails Way.” The code gets cluttered with parentheses and strings, losing that fluid readability that Ruby is known for.

The Solution: Turning the Array into an Inquirer

By calling .inquiry on an array, Rails wraps that list in an ActiveSupport::ArrayInquirer object. This allows you to ask questions using methods ending in ?.

Practical Example:

1
2
3
4
5
roles = ["admin", "editor"].inquiry

roles.admin?  # => true
roles.editor? # => true
roles.guest?  # => false

You can also check for multiple items at once by passing arguments:

1
roles.any?(:admin, :moderator) # => true

Why It Matters