Simplify multiple is_a? calls on object
Create an is_any?
method.
If you are doing this often, it might be best to create an initializer (or any file that gets loaded in if you're not using Rails) that adds a new method called is_any?
to Object
.
Initializer
config/initializers/is_any.rb
class Object
def is_any?( *klasses ) # Using the splat and flatten allows this to accept
klasses.flatten.any? do |klass| # both comma separated params as well as an Array.
self.is_a?( klass )
end
end
end
Usage
actor.is_any? Array, Hash
or
actor.is_any? [ Array, Hash ]
You're looking for Array#any?
actor.inspect if [Array, Hash].any? { |c| actor.is_a? c }
#each
usually just returns the enumerable. #any?
ors together the result of the blocks.
Use .include?
Instead of using .is_a?
for class type, you can also put all the classes in an Array
and then see if the object's class is included in that Array
, for example:
[ Array, Hash ].include?( actor.class )
NOTE: This will not check subtypes, like is_a?
will.
If you want to match exact classes (and not descendants), you can use:
[Hash, Array].member? a.class
I think you should explain what exactly you need to achieve. Perhaps the only thing you need to check is if your object is an Enumerable
or not, or even if it respond_to?
some particular method.