Iggy Iggy - 3 months ago 11
Ruby Question

Remove a string pattern and symbols from string

I need to clean up a string from the phrase

"not"
and hashtags(
#
). (I also have to get rid of spaces and capslock and return them in arrays, but I got the latter three taken care of.)

Expectation:

"not12345" #=> ["12345"]
" notabc " #=> ["abc"]
"notone, nottwo" #=> ["one", "two"]
"notCAPSLOCK" #=> ["capslock"]
"##doublehash" #=> ["doublehash"]
"h#a#s#h" #=> ["hash"]
"#notswaggerest" #=> ["swaggerest"]


This is the code I have

def some_method(string)
string.split(", ").map{|n| n.sub(/(not)/,"").downcase.strip}
end


All of the above test does what I need to do except for the hash ones. I don't know how to get rid of the hashes; I have tried modifying the regex part:
n.sub(/(#not)/)
,
n.sub(/#(not)/)
,
n.sub(/[#]*(not)/)
to no avail. How can I make Regex to remove
#
?

Answer
arr = ["not12345", "   notabc", "notone, nottwo", "notCAPSLOCK",
       "##doublehash:", "h#a#s#h", "#notswaggerest"].

arr.flat_map { |str| str.downcase.split(',').map { |s| s.gsub(/#|not|\s+/,"") } }
  #=> ["12345", "abc", "one", "two", "capslock", "doublehash:", "hash", "swaggerest"]

When the block variable str is set to "notone, nottwo",

s = str.downcase
  #=> "notone, nottwo" 
a = s.split(',')
  #=> ["notone", " nottwo"] 
b = a.map { |s| s.gsub(/#|not|\s+/,"") }
  #=> ["one", "two"] 

Because I used Enumerable#flat_map, "one" and "two" are added to the array being returned. When str #=> "notCAPSLOCK",

s = str.downcase
  #=> "notcapslock" 
a = s.split(',')
  #=> ["notcapslock"] 
b = a.map { |s| s.gsub(/#|not|\s+/,"") }
  #=> ["capslock"]