Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda