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

169
Visualizações
ruby reorder array of symbols in one pass

I am looking for the most efficient way to do this. Anything with a hyphen must be in before any symbols without a hyphen in the array. My naive solution filters the array twice and concats. I feel like there should be a way to do this in one pass instead of two.

input = [:en, :de, :es, :"es-MX", :fr, :ko, :"ko-KR", :"en-GB"]

output = [:"es-MX", :"ko-KR", :"en-GB", :en, :de, :es, :fr]

Naive solution:

def reorder(input)
  ## find everything with a hypen
  output = input.select { |l| 
    l.to_s.include?('-')
  }

  # find everything without a hyphen and concat to output
  output.concat(input.reject { |l| 
    l.to_s.include?('-')
  })
end
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

This is a sorting task, so it makes the most sense to me to simply use Enumerable#sort_by:

# Put symbols with hyphens first
input.sort_by { |s| s.to_s.include?('-') ? 0 : 1 }

If you want to sort by something else within those categories, you can do something like this:

# Put symbols with hyphens first, then sort in alphabetical order
input.sort_by { |s| [s.to_s.include?('-') ? 0 : 1, s] }
over 4 years ago · Santiago Trujillo Relatório

0

You can filter the array in one pass with Array#partition:

def reorder(input)
  a, b = input.partition { |l| l.to_s.include?('-') }

  a.concat(b)
end
over 4 years ago · Santiago Trujillo Relatório

0

input = [:en, :de, :es, :"es-MX", :fr, :ko, :"ko-KR", :"en-GB"]

code

p input.partition{|x|x.to_s.include?'-'}.flatten

Output

[:"es-MX", :"ko-KR", :"en-GB", :en, :de, :es, :fr, :ko]
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