Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda