Posted about 6 years ago. Visible to the public.

ArrayInquirer provides friendlier way to check contents in an array

Rails 5 introduces ArrayInquirer 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 =[:cat, :dog, 'rabbit']) > #=> 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 =[: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, it's any? method performs same as any? method of Array class when no arguments are passed.

pets =[: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 > #=> 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 > #=> true > request.variant.tablet? #=> false

Owner of this card:

Alexander M
Last edit:
about 6 years ago
by Alexander M
Posted by Alexander M to Ruby and RoR knowledge base
This website uses short-lived cookies to improve usability.
Accept or learn more