Posted over 5 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.

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

Copy
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, it's any? method performs same as any? method of Array class when no arguments are passed.

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

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

Copy
request.variant = :phone > request.variant #=> [:phone] > request.variant.include?(:phone) #=> true > request.variant.include?('phone') #=> false

Corresponding Rails 5 version is below.

Copy
request.variant = :phone > request.variant.phone? #=> true > request.variant.tablet? #=> false

Owner of this card:

Avatar
Alexander M
Last edit:
over 5 years ago
by Alexander M
Tags:
Rails-5-0
Posted by Alexander M to Ruby and RoR knowledge base
This website uses short-lived cookies to improve usability.
Accept or learn more