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

172
Views
Ruby reordena la matriz de símbolos en una sola pasada

Estoy buscando la manera más eficiente de hacer esto. Todo lo que tenga un guión debe estar antes que cualquier símbolo sin guión en la matriz. Mi solución ingenua filtra la matriz dos veces y concatena. Siento que debería haber una manera de hacer esto en una sola pasada en lugar de dos.

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

Solución ingenua:

 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 answers
Answer question

0

Esta es una tarea de clasificación, por lo que tiene más sentido para mí simplemente usar Enumerable#sort_by :

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

Si desea ordenar por otra cosa dentro de esas categorías, puede hacer algo como esto:

 # 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 Report

0

Puede filtrar la matriz en una sola pasada con Array#partition:

 def reorder(input) a, b = input.partition { |l| l.to_s.include?('-') } a.concat(b) end
over 4 years ago · Santiago Trujillo Report

0

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

código

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

Producción

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