Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
How to check if a model is present in an Array in Ruby

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!

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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) }
over 4 years ago · Santiago Trujillo Report

0

The easiest solution:

you can simply check whether the array contains Profile object using:

array = [Profile1, Profile2, Article1]
array.any?(Profile)

and similarly for Article:

array.any?(Article)

Thanks

over 4 years ago · Santiago Trujillo Report

0

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!