我熟悉如何检查字符串是否包含子字符串,也熟悉如何检查单个字母是数字还是字母,但是我将如何检查字符串中是否有任何字母?

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

最佳答案

我认为,您可以尝试类似的方法:

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

如果您不想使用正则表达式。如果字符串中有任何字母,此方法将返回 true:
> letters? 'asd'
 => true
> letters? 'asd123'
 => true
> letters? '123'
 => false

关于ruby - 当字符串包含任何字母 A-Z 或 a-z 时,如何返回 true 或 false?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39644702/

10-13 07:12