From: Robert Klemme Date: 2010-10-28T17:47:23+09:00 Subject: Re: ctype functionality without a gem? On Thu, Oct 28, 2010 at 9:50 AM, Ammar Ali wrote: > Is there a built-in method for identifying character types a la > ctype() in C? I would like to avoid requiring a gem dependency. No other than regexp as far as I know. > I'm considering the following approach, if nothing exists, but it > seems like overkill to me. > > def ctype(c) >  case c >  when /[[:alnum:]]/; :alnum >  when /[[:alpha:]]/; :alpha >  # etc... >  end > end > > def alnum?(c); ctype(c) == :alnum end > def alpha?(c); ctype(c) == :alpha end > # etc... 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+)/ =~ 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 => ["foo", "bar", "123"] Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/