Rails 5 ArrayInquirer and checking array contents

Mohit Natoo

By Mohit Natoo

on 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.

1
2pets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit'])
3
4> pets.cat?
5#=> true
6
7> pets.rabbit?
8#=> true
9
10> pets.elephant?
11#=> false
12

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

1
2pets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit'])
3
4> pets.any?(:cat, :dog)
5#=> true
6
7> pets.any?('cat', 'dog')
8#=> true
9
10> pets.any?(:rabbit, 'elephant')
11#=> true
12
13> pets.any?('elephant', :tiger)
14#=> false
15

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

1
2pets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit'])
3
4> pets.any?
5#=> true
6
7> pets.any? { |pet| pet.to_s == 'dog' }
8#=> true
9

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.

1
2pets = [:cat, :dog, 'rabbit'].inquiry
3
4> pets.cat?
5#=> true
6
7> pets.rabbit?
8#=> true
9
10> pets.elephant?
11#=> false
12

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.

1
2request.variant = :phone
3
4> request.variant
5#=> [:phone]
6
7> request.variant.include?(:phone)
8#=> true
9
10> request.variant.include?('phone')
11#=> false
12

Corresponding Rails 5 version is below.

1
2request.variant = :phone
3
4> request.variant.phone?
5#=> true
6
7> request.variant.tablet?
8#=> false
9

If you liked this blog, you might also like the other blogs we have written. Check out the full archive.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, React.js, React Native, remote work,open source, engineering & design.