From: Michael Morin Date: 2008-08-16T19:42:30+09:00 Subject: Re: Idiom of removing a particular character from a String? 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? > > Lorenzo > > There have been some good solutions posted already. However, I don't think I'd want to be repeating them many times (or at all) in my code. Whichever solution you use, it's probably best to hide it away in the String class somewhere, else your code will suddenly start looking... perl-like. This seems sensible to me. If you're on 1.8.7 or 1.9 (I am not), you can also use the tap method. class String def rem(idx) c = clone c[idx..idx] = "" c end def rem!(idx) self[idx..idx] = "" self end end If you're on 1.8.7, 1.9 or feel like implementing it yourself, you can use the tap method. Using the tap method seems cleaner. unless Object.methods.include? "tap" class Object def tap yield self self end end end class String def rem(idx) clone.tap {|t| t[idx..idx] = "" } end def rem!(idx) tap {|t| t[idx..idx] = "" } end end -- Michael Morin Guide to Ruby http://ruby.about.com/ Become an About.com Guide: beaguide.about.com About.com is part of the New York Times Company