From: Chad Perrin Date: 2011-07-15T12:16:40+09:00 Subject: Re: Is there a more efficient way to remove data from a string? --SUOF0GtieIMvvwua Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Jul 15, 2011 at 10:52:54AM +0900, Josh Cheek wrote: >=20 > Depending on how the string is to be interpreted, you may need to escape = it > before creating it: >=20 > str =3D "a.b" > /#{str}/ # =3D> /a.b/ > Regexp.new str # =3D> /a.b/ > Regexp.new Regexp.escape str # =3D> /a\.b/ That's a very good point. Things get tricky when you start stuffing strings into regexen and so on. If you (in general -- not Josh Cheek, per se) are not yet familiar with the various unit testing libraries available for Ruby, now might be a good time to familiarize yourself at least with the basics of Test::Unit, the Ruby standard library's equivalent to NUnit. >=20 > Depending on how big the files are, efficiency may be very important. In > that case, you might benchmark a few different approaches and see which is > best. Here is another possibility: > ARGF.each_line do |line| > index =3D line.index regex > line.slice!(index..-1) if index > puts line > end This looks to me like it is likely to be more resource-intensive than my example, thanks to the sheer number of operations involved, and the fact that I do not think .* would impose too much additional overhead on the regex match -- though maybe the interpolation in my version would be somewhat expensive. Then again, I don't know much about the implementation of methods that come with the language, so don't just take my word for it. As Josh suggests, you should at least loosely benchmark performance of various implementations if you find your first attempt is not performing well enough for your needs. --=20 Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ] --SUOF0GtieIMvvwua Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.14 (FreeBSD) iEYEARECAAYFAk4frTwACgkQ9mn/Pj01uKUzQACfe/HhxFOYnc1tu0YDNm5MQZcm 3ZMAoNIpIOLLSAoGfOlULpJEoUDTAUYN =E5UY -----END PGP SIGNATURE----- --SUOF0GtieIMvvwua--