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

163
Views
¿Hay alguna manera de comparar dos matrices y devolver una nueva matriz de los elementos comunes que tienen el mismo índice?

Por ejemplo

 a = [2,3,1,1] b = [2,7,4,2] --> c = [2]

Mi solución fue:

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

Pero si lo aplico al ejemplo dado, devuelve

 c = [2,2]
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Dado que desea comparar matrices por elementos, zip sería una excelente opción aquí.

 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 Report

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| toma el primer elemento de b (que es 2). b.index(em) encuentra el primer índice que contiene un 2, que es el primero . (índice 0). Dado que la matriz a tiene un 2 en el mismo índice, todo el bloque es verdadero y se selecciona el elemento 2. Pero la misma historia es cierta para el último elemento. Nuevamente, se busca en la matriz b y el primer 2 se encuentra en el índice 0. Por lo tanto, ese 2 también se selecciona.

 a.each_with_index.to_a & b.each_with_index.to_a

le daría los elementos comunes y sus índices.

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!