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 end
Analogous, we can do this with digits as well:
def all_digits(str) str[/[0-9]+/] == str end def all_letters_or_digits(str) str[/[a-zA-Z0-9]+/] == str end
Of course, it’s even better if you make these methods a core extension of String itself

Leave a Reply