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

166
Vistas
Is there a way to compare two arrays and return a new array of the common elements which have the same index?

For example

a = [2,3,1,1]
b = [2,7,4,2]

--> c = [2]

My solution was:

c = b.select do
    |em| b.index(em) == a.index(em)
    end

But if I apply it to the given example it returns

c = [2,2]
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Since you want to compare arrays element-wise, zip would be an excellent choice here.

a.zip(b) # => [[2, 2], [3, 7], [1, 4], [1, 2]]

a.zip(b).select {|a1, b1| a1 == b1}.map(&:first) # [2]

# or in ruby 2.7+
a.zip(b).filter_map {|a1, b1| a1 == b1 && a1} # [2]
over 4 years ago · Santiago Trujillo Denunciar

0

a = [2,3,1,1]
b = [2,7,4,2]
c = b.select do |em|
  b.index(em) == a.index(em)
end

b.select do |em| takes the first element of b (which is 2). b.index(em) finds the first index which contains a 2, which is the first one. (index 0). Since array a has a 2 on the same index, the whole block is true and the element 2 is selected. But the same story is true for the last element. Again, the b array is searched and the first 2 is found at index 0. Hence, that 2 is also selected.

a.each_with_index.to_a & b.each_with_index.to_a

woud give you the common element(s) and their indices.

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