Home > Net >  How to check if a model is present in an Array in Ruby
How to check if a model is present in an Array in Ruby

Time:04-02

I have an array, and the elements inside are a mix of 2 models: Article and Profile.

Is there a way to check if there is an Article and/or Profile model inside the array? The functions I saw like include? work for the specific elements and not their class.

Example: Given [Profile1, Profile2, Article1] I wanted to check if there is an Article or Profile in there. I can only check if there is an element named Profile1.

Any help would be much appreciated! Thank you!

CodePudding user response:

You can use the method any? with the method is_a?

Here is a way to know if there is an Article or a Profile in the array.

array = [Profile1, Profile2, Article1]
array.any? { |a| a.is_a?(Article) || a.is_a?(Profile) }

CodePudding user response:

You can even use instance_of?

array = [Profile1, Profile2, Article1]
array.any?{ |v| v.instance_of?(Profile) || v.instance_of?(Article) }

If you want count every models, you can do like this:

For Article

array = [Profile1, Profile2, Article1]
array.map{ |v| v.instance_of?(Article) }.count(true)

For Profile

array.map{ |v| v.instance_of?(Profile) }.count(true)
  • Related