Forum: Ruby short cut for gsub("word","")

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
525128e48ca2b4c7fb6176ea166fccfd?d=identicon&s=25 Eric G. (gotskill10)
on 2009-04-14 00:20
is there any shortcut for removing a string of characters from text,
like gsub("word",""). I looked into String#delete but it will delete all
the characters in the entire word.

Im guessing something like this already exists.
2f55791ab9018b4d01fb741fab21843d?d=identicon&s=25 Tony Arcieri (Guest)
on 2009-04-14 01:41
(Received via mailing list)
On Mon, Apr 13, 2009 at 4:20 PM, Aryk Grosz
<tennisbum2002@hotmail.com>wrote:

> Im guessing something like this already exists.
>

I'm kind of surprised String#- doesn't work (it isn't defined)
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2009-04-15 15:15
Aryk Grosz wrote:
> is there any shortcut for removing a string of characters from text,
> like gsub("word",""). I looked into String#delete but it will delete all
> the characters in the entire word.

  str["word"] = ""
  str[/word/] = ""

but these only do the first instance.

If you find yourself writing

  str.gsub! /word/, ''

repeatedly, to the point where it is tiresome, then factor it out
yourself, depending on exactly what your needs are. e.g.

  class String
    def remove!(str)
      gsub!(str, '')
    end
    def remove(str)
      res = dup
      res.remove!(str)
      res
    end
  end
This topic is locked and can not be replied to.