From: "Lorenzo E. Danielsson" Date: 2008-08-15T01:59:51+09:00 Subject: Re: Idiom of removing a particular character from a String? On Thu, 2008-08-14 at 23:40 +0900, Gregory Seidman wrote: > On Thu, Aug 14, 2008 at 11:21:10PM +0900, Lorenzo E. Danielsson wrote: > > 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? > > str[index..index] = "" So: str = "hello" rem = str.clone rem[2,1] = "" # => "helo" rem Sorry, but that doesn't look any cleaner than my solution. I was looking for something like: class String def delete_at(i) str = self.clone str[i] = "" end end str = "hello" rem = str.delete_at(2) # => "helo" That is, original string does not get tampered with. Resulting string is original string minus exactly one character, at the specified index. The above works, but I was hoping to avoid that by using some neat idiom. This is not really a problem, but 99.x % of the time, Ruby does things in a way that are so cool that I tend to get lazy and expect it to always behave that way. The few times it doesn't, it comes as a shock. > > > Lorenzo > --Greg > >