如果使用Regex在Ruby中声明
除了注释行之外,一切似乎都正常工作:
#return false if not s[0].upcase =~ /AZ/
和第四次检查。
s[0]
和/AZ/
比较的正确if
语句是什么?
def starts_with_consonant?(s) return false if s.length == 0 #return false if not s[0].upcase =~ /AZ/ n = "AEIOU" m = s[0] return true if not n.include? m.upcase false end puts starts_with_consonant?("Artyom") # false 1 puts starts_with_consonant?("rtyom") # true 2 puts starts_with_consonant?("artyom") # false 3 puts starts_with_consonant?("$rtyom") # false 4 puts starts_with_consonant?("") # false 5
试试这个…
def starts_with_consonant? s /^[^aeiou\d\W]/i =~ s ? true : false end
我也不确定你的正则表达式想要实现什么,所以我不能建议修复。 但是对于整个方法,我会通过使用===运算符并使用i
选项使正则表达式不区分大小写来保持简单:
def starts_with_consonant?(s) /^[bcdfghjklmnpqrstvwxyz]/i === s end
正则表达式很容易:
def starts_with_consonant?(s) !!(s =~ /^[bcdfghjklmnpqrstvwxyz]/i) end
这匹配字符串的第一个字符和辅音集。 !!
强制输出为true / false。
这也有效
def starts_with_consonant? s return /^[^aeiou]/i === s end