Home > Software engineering >  How could I delete 50% of the smileys from a text, selected randomly, with Ruby?
How could I delete 50% of the smileys from a text, selected randomly, with Ruby?

Time:04-01

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.

CodePudding user response:

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

CodePudding user response:

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.
  • Related