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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With