Doesn't Ruby have isalpha?

There's a special character class for this:

char.match(/^[[:alpha:]]$/)

That should match a single alphabetic character. It also seems to work for UTF-8.

To test a whole string:

string.match(/^[[:alpha:]]+$/)

Keep in mind this doesn't account for spaces or punctuation.


You can roll your own :) Replace alnum with alpha if you want to match only letters, without numbers.

class String
  def alpha?
    !!match(/^[[:alnum:]]+$/)
  end
end

'asdf234'.alpha? # => true
'asdf@#$'.alpha? # => false

The python function only works for ASCII chars; the [[:alnum]] regex would do things like "tëst".alpha? => true. match/\w/ matches underscores, so that leaves

def isalpha(str)
  return false if str.empty?
  !str.match(/[^A-Za-z]/)
end

to reproduce the Python behaviour.

Tags:

Ruby