Ruby: Checking if a string is all letters

Looking at the stats on my previous post, I noticed a lot of people are wrongly redirected when they’re looking for a solution to check if a ruby string is all letters. For those, I’d like to post my solution, which is imo a clean way of doing it:

def all_letters(str)
	# Use 'str[/[a-zA-Z]*/] == str' to let all_letters
	# yield true for the empty string
	str[/[a-zA-Z]+/]  == str

Analogous, we can do this with digits as well:

def all_digits(str)
	str[/[0-9]+/]  == str

def all_letters_or_digits(str)
	str[/[a-zA-Z0-9]+/]  == str

Of course, it’s even better if you make these methods a core extension of String itself 🙂


~ by moiristo on June 4, 2009.

7 Responses to “Ruby: Checking if a string is all letters”

  1. I found this helpful, thanks!

  2. Thanks so much

  3. Thanks, this was the only understandable tutorial I could find after a lot of searching 🙂

  4. “test5″[/[a-zA-Z]/] == “test” returns true, unfortunately.

  5. Looks like the solution is to add ^ and $ to specify the beggining and end of your string like so:

    “test5″[/^[a-zA-Z]$/] == “test” returns false

  6. I forgot the +, but the point is you need ^ and $

  7. Hi Jean, thanks for your interest. I don’t think the snippet needs to be changed though. The point is that I’m comparing the regexed value against the original value. Taking your example, the comparison made would be:

    “test5″[/[a-zA-Z]/] == “test5”

    …which returns false.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: