Search code examples
rubyregexstringruby-1.9gsub

Is there a Regex Delete in Ruby?


All of my string delete's with regex use gsub, is there a shorter way? string.gsub(/\A.*\//,'')


Solution

  • One way is to add your own short methods:

    class String
    
      def del(regexp)
        gsub(regexp,'')
      end
    
      def del!(regexp)
        gsub!(regexp,'')
      end
    
    end
    

    Typically this code would go in a lib/ directory, for example lib/string-extensions.rb

    Heads up that some programmers really dislike this because it's monkey-patching. I personally like it for projects because it makes code easier to understand - once I have the "del" method, I can quickly see that calls to it are just deleting the regexp.