From: "Lorenzo E. Danielsson" Date: 2008-08-15T02:09:53+09:00 Subject: Re: Idiom of removing a particular character from a String? On Thu, 2008-08-14 at 23:52 +0900, Michael Libby wrote: > On Thu, Aug 14, 2008 at 9:21 AM, Lorenzo E. Danielsson > wrote: > > Hi all, > > > > Is there any particular idiom for removing a particular character from a > > string *by index* and returning the resulting string? The following > > makes my old eyes sore: > > > > rem = str.clone > > rem[i] = "" > > rem > > > > as does this: > > > > rem = str.scan(/./) > > rem.delete_at(i) > > rem.to_s > > > > It seems there should be some more idiomatic way to do this, something > > like str.annihilate_char_at_index_possibly_without_a_bang(i), read as > > String#delete_at(i) and String#delete_at!(i). Of course these methods > > don't exist, and "".methods doesn't turn up anything interesting. So > > what is a *decent* way of performing this? > > irb(main):022:0> rem = "foobar" > => "foobar" > irb(main):023:0> rem.slice!(3).chr > => "b" > irb(main):024:0> rem > => "fooar" The "problem" is that slice does not return the resulting string but rather the sliced portion. This is of course not a problem in itself, it is rather the expected behavior of slice. But, in my particular case that *still* leads to: str = "hello" rem = str.clone rem.slice!(2) rem # => "helo" Whereas I would have wanted: str = "hello" rem = str.slice_and_return_everything_but_the_sliced_part(2) This is partly a matter of laziness on my part, that I prefer to type two lines instead of four. But, it is also a matter that it kind of breaks the POLS, at least for me. I have grown accustomed to being able to perform: result = original.some_method(args) and have the result be some mutilated form of original, with original being left intact. So when String#delete_at(index) doesn't work, it feels like it *should* have worked.. Anyways, nothing worth losing sleep over.. > > -Michael >