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

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

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 Report

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 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!