From: Keith Johnston Date: 2008-10-01T21:58:05+09:00 Subject: Re: String delete method help Hi, Yes, that helped. I was able to achieve what I thought the delete function was doing by using String#sub! with a regular expression to remove any charaters between "http" and "com". string = "http://groups.google.com/group/ruby-talk-google/".sub!(/ http.*com/, "") Thanks, On Oct 1, 12:58 pm, Stefano Crocco wrote: > Alle Wednesday 01 October 2008, Keith Johnston ha scritto: > > > > > Hi, > > > I have a string which hold a URL. I'm trying to use the string .delete > > method to remove the domain from the url but it isn't working as I > > thought it should from the docs. > > > For example: > > > string = "http://groups.google.com/group/ruby-talk-google/" > > > I want to remove the "http://groups.google.com" part of the string, so > > I tried: > > > string.delete('http', 'com') > > > thinking this would delete everything between 'http' and 'com' but all > > I get is the entire string without any changes and with no errors. > > > I'm probably misunderstanding how the delete function works - can > > someone explain? > > > Thanks, > > There are two reasons for which your code doesn't do what you want: > * String#delete is a non-destructive method, that is it doesn't change its   > receiver but creates a new string which is a copy of the receiver, modifies it > and returns it: > > str = "abc" > str1 = str.delete 'a' > puts str > => "abc" > puts str1 > => "bc" > > If you want to modify the string in place, use String#delete!, instead > > * String#delete removes from the string the characters which are the > intersection between its arguments. This means that a) it works character- > wise, so calling str.delete("abc") will delete all 'a', all 'b' and all 'c', > not just all instances of the substring 'abc'; b) in your case, the two > strings you pass to delete have no characters in common, so none will be > removed. > > One way to do what you want is to use sub!: > > string = "http://groups.google.com/group/ruby-talk-google/" > string.sub!("http://groups.google.com", '') > > I hope this helps > > Stefano