Rails 5 ArrayInquirer and checking array contents

Mohit Natoo

Mohit Natoo

May 27, 2016

This blog is part of our  Rails 5 series.

Rails 5 introduces Array Inquirer that wraps an array object and provides friendlier methods to check for the presence of elements that can be either a string or a symbol.


pets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit'])

> pets.cat?
#=> true

> pets.rabbit?
#=> true

> pets.elephant?
#=> false

Array Inquirer also has any? method to check for the presence of any of the passed arguments as elements in the array.


pets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit'])

> pets.any?(:cat, :dog)
#=> true

> pets.any?('cat', 'dog')
#=> true

> pets.any?(:rabbit, 'elephant')
#=> true

> pets.any?('elephant', :tiger)
#=> false

Since ArrayInquirer class inherits from Array class, its any? method performs same as any? method of Array class when no arguments are passed.


pets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit'])

> pets.any?
#=> true

> pets.any? { |pet| pet.to_s == 'dog' }
#=> true

Use inquiry method on array to fetch Array Inquirer version

For any given array we can have its Array Inquirer version by calling inquiry method on it.


pets = [:cat, :dog, 'rabbit'].inquiry

> pets.cat?
#=> true

> pets.rabbit?
#=> true

> pets.elephant?
#=> false

Usage of Array Inquirer in Rails code

Rails 5 makes use of Array Inquirer and provides a better way of checking for the presence of given variant.

Before Rails 5 code looked like this.


request.variant = :phone

> request.variant
#=> [:phone]

> request.variant.include?(:phone)
#=> true

> request.variant.include?('phone')
#=> false

Corresponding Rails 5 version is below.


request.variant = :phone

> request.variant.phone?
#=> true

> request.variant.tablet?
#=> false

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.