From: Anton Bangratz Date: 2010-10-28T19:02:09+09:00 Subject: Re: ctype functionality without a gem? --------------enig069ECF57B926919ED344F75C Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable On 10/28/2010 11:16 AM, Ammar Ali wrote: > On Thu, Oct 28, 2010 at 11:47 AM, Robert Klemme > wrote: >> On Thu, Oct 28, 2010 at 9:50 AM, Ammar Ali wro= te: >>> Is there a built-in method for identifying character types a la >>> ctype() in C? I would like to avoid requiring a gem dependency. >=20 >> What do you need that for? Why not directly use a regexp to match a >> string? Often you can use capturing groups in a single regexp, e.g. >> >> irb(main):009:0> %w{foo bar 123}.each do |s| >> irb(main):010:1* if /(\d+)|(\w+)/ =3D~ s >> irb(main):011:2> puts "number" if $1 >> irb(main):012:2> puts "chars" if $2 >> irb(main):013:2> end >> irb(main):014:1> end >> chars >> chars >> number >> =3D> ["foo", "bar", "123"] >=20 > That's very cool. I'll have to remember that one. It is a bit brittle, though. Watch: %w{foo bar 123 345bar}.each do |s| if /(\d+)|(\w+)/ =3D~ s puts "number" if $1 puts "chars" if $2 end end #=3D> chars chars number number >=20 > I do actually need to test if a character is of a certain type, all by > itself, as part of a parser I'm working on. I came up with this quick > solution for now, http://gist.github.com/650968 >=20 > Thanks, > Ammar >=20 >=20 This is similarily fragile. If you are only testing for one character, it seems good, if you are going to test for strings, it will not be enough. Also, the whole solution is not necessarily fast - I do love regular expressions, but I would search on for other methods to meet your requirements. It really depends on what your goal is. If it is about bit streams, you might want to look into bit-struct or similar approaches that use Array#pack and String#unpack. Regards, t. --=20 Anton Bangratz - Key ID 363474D1 - http://tony.twincode.net/ fortune(6): If I love you, what business is it of yours? -- Johann van Goethe --------------enig069ECF57B926919ED344F75C Content-Type: application/pgp-signature; name="signature.asc" Content-Description: OpenPGP digital signature Content-Disposition: attachment; filename="signature.asc" -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.14 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJMyUoZAAoJEAgZMsE2NHTR+A4IALe57jZTcbNgiJ5DYPoPO1BG ASbuQpJbRS/zsA7Lo2qXuYUVwTMAQuDCqA7vHGoHxisipVVZ/HwA2CFzy17Y1BhX U1+Z90MfrKOmcUjfbwgNYYfk9ev0MnZnGX7VJtlJKsKyCcTx4mLtvJA5qDAT0nwk 645moLiLHLPb61jmedE/bYEYyPkVO06Ymg12LzyBasOz+o0zNibISdhNZTgmWVeO zmWyFmX9ZfEFzfht0letjS/EqlgTh9sw4ged0QXLxhEu1aZFrT9hIb+mWkNxMopn Nzgdotmr/lseojhi5ewvk18MCBUbIE6RAGkNiNh7A7MNhjkVDJoeWke45ZDrB2Q= =lv/y -----END PGP SIGNATURE----- --------------enig069ECF57B926919ED344F75C--