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

265
Vistas
How could I delete 50% of the smileys from a text, selected randomly, with Ruby?

For example:

"Hi! How :) are :) you? I'm :) fine.:)".magic()
=> "Hi! How are :) you? I'm fine.:)"
or
=> "Hi! How are :) you? I'm :) fine."
or
...

Only :) smiley should be supported for deletion or replacing.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Use:

  • String#scan to get all occurences of the smiley
  • Array#sample to make a random selection of which to remove
  • String#gsub with a block parameter to iterate through matches and select positions to substitute with empty string

Code:

class String
  def magic()
    len = scan(/:\)/).length
    pos_to_remove = (0 ... len).to_a.sample(len / 2)
    gsub(/:\)/).with_index { |_, i|
      if pos_to_remove.include?(i) then "" else ":)" end
    }
  end
end
over 4 years ago · Santiago Trujillo Denunciar

0

The key is to match two :) at the same time but only capture one of them in the group.

  • regex
(:\).*?):\)\s*

or

:\)\s*(.*?:\))
  • substitution
\1

See the test case here

"Hi! How :) are :) you? I'm :) fine.:)".gsub(/(:\).*?):\)\s*/, '\1')
# => Hi! How :) are you? I'm :) fine.
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