I would like to remove all substrings from a string that begin with a pound sign and end in a space or are at the end of the string. I have a working solution, but I'm wondering if there's a more efficient (or equally efficient but less wordy) approach.
For example, I want to take "leo is #confused about #ruby #gsub"
and turn it into "#confused #ruby #gsub"
.
Here is my solution for now, which involves arrays and subtraction.
strip_spaces = str.gsub(/\s+/, ' ').strip()
=> "leo is #confused about #ruby #gsub"
all_strings = strip_spaces.split(" ").to_a
=> ["leo", "is", "#confused", "about", "#ruby", "#gsub"]
non_hashtag_strings = strip_spaces.gsub(/(?:#(\w+))/) {""}.split(" ").to_a
=> ["leo", "is", "about"]
hashtag_strings = (all_strings - non_hashtag_strings).join(" ")
=> "#confused #ruby #gsub"
To be honest, now that I'm done writing this question, I've learned a few things through research/experimentation and become more comfortable with this array approach. But I still wonder if anyone could recommend an improvement.