I am trying to write a regex that takes a word and returns true for words starting with a vowel and returns false for words starting with a consonant. I have never written regex before, and I'm a little confused on how to write the expression. This is what I have so far:
def starts_with_a_vowel?(word)
if word.match(/\A+[aeiou]/) == true
return true
else
return false
end
end
Edit: So if word = "boat" , expression should return false. If word = "apple", expression should return true.
word.match? /\A[aeiou]/i
is literally all you need. (ruby >= 2.4)
It matches the beginning of the string \A
followed by a vowel [aeiou]
in a case-insensitive manner i
returning a bool word.match?
Before ruby 2.4 you have to use word.match
and convert it to a bool, which is easiest done by logically negating it twice with !!
EDIT:
OK.. So.. I never tested the code I formerly wrote.. it was meant only as some suggestion how to use the match
with regex, but it not worked at all.. (that code snippet is now attached to the end of my answer fyi)
this here should be the working one:
def starts_with_a_vowel?(word)
!!word.capitalize.match(/\A+[AEIOU]/)
end
..but how it was mentioned by Eric Duminil here below in comments, the method/function is not needed
!!word.capitalize.match(/\A+[AEIOU]/)
can be used directly..
it returns true
or false
but there are surely other (maybe better) solutions too..
..and here is the NOT working code, which I formerly wrote:
def starts_with_a_vowel?(word)
return word.match(/\A+[aeiou]/).length > 0
end
..the match
method returns nil
when not match and because nil
has no length
method defined, it raises NoMethodError
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