Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't Ruby have isalpha?

Tags:

ruby

Like Python? I'm trying to check whether each character in a string is an alphanumeric or not?

like image 806
sivabudh Avatar asked May 17 '12 14:05

sivabudh


2 Answers

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.

like image 179
tadman Avatar answered Sep 20 '22 02:09

tadman


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
like image 35
Sergio Tulentsev Avatar answered Sep 17 '22 02:09

Sergio Tulentsev