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

151
Vistas
Sorting an array according to an element inside this array

I need to order my array according to an element of it, the reference element can vary. For example, I would like the 3 to become the first element of the array and the 1, 2 to be put at the end.

  • array = [1, 2, 3, 4, 5, 6]
  • new_array = [3, 4, 5, 6, 1, 2]

The element may vary. If I start from 5, the behavior must be the same: the elements that precede are placed at the end, so I will have :

  • new_array = [5, 6, 1, 2, 3, 4]
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

If I understand correctly you want to rotate the array.

array
# [1, 2, 3, 4, 5, 6]
array.rotate(2) # or array.rotate(array.index(3))
# [3, 4, 5, 6, 1, 2]

https://apidock.com/ruby/v2_5_5/Array/rotate

over 4 years ago · Santiago Trujillo Denunciar

0

Definitely use #rotate for this in actual use, but as an alternative, you could do something like #shift and #push until the desired element is at the beginning of the array.

def rotate(arr, elem)
    arr2 = arr.clone
    arr2.push(arr2.shift) until arr2.first == elem
    arr2
end
irb(main):026:0> arr = [1, 2, 3, 4, 5, 6]
=> [1, 2, 3, 4, 5, 6]
irb(main):027:0> rotate(arr, 3)
=> [3, 4, 5, 6, 1, 2]
irb(main):028:0> arr
=> [1, 2, 3, 4, 5, 6]

Clearly, if elem is not in arr, this will run forever. You could implement some kind of check to ensure this doesn't happen, but that's just one reason you shouldn't actually do this as anything other than a learning exercise.

One approach would be to find the index of elem in arr and shift/push that many times. The &. operator may be useful in that situation to deal with the possibility of not finding elem in arr.

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