Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return true or false when a string contains any letters A-Z or a-z?

Tags:

ruby

I am familiar with how to check if a string contains a substring, and also familiar with how to check if a single letter is a number or a letter, but how would I go about checking a string for any letters?

def letters?(string)
  # what do i do here?
end

# string could be anything from '111' to '1A2' to 'AB2589A5' etc...

string = '1A2C35'
if letters?(string) == true
  # do something if string has letters
else
  # do something else if it doesnt
end
like image 938
alilland Avatar asked Oct 15 '25 16:10

alilland


2 Answers

The proper way to check if the string contains any letter, is to use \p{L} matcher. That way you’ll match

"ï" # in "naĩve"

as well as

"ç" # in Barça

The code would be:

def letters? string
  !string[/\p{L}/].nil?
end
like image 178
Aleksei Matiushkin Avatar answered Oct 18 '25 07:10

Aleksei Matiushkin


I think, you can try something like it:

def letters?(string)
   string.chars.any? { |char| ('a'..'z').include? char.downcase }
end

If you don't wanna use regexp. This method return true if there are any letters in the string:

> letters? 'asd'
 => true 
> letters? 'asd123'
 => true 
> letters? '123'
 => false 
like image 28
Alex Holubenko Avatar answered Oct 18 '25 07:10

Alex Holubenko